1

I have a canvas that I can draw things what I want to do is generate new canvases dynamically when clicking a button.I've defined a generate function but it did not work

here is script

//<![CDATA[ 
window.addEventListener('load', function () {
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');

// create a drawer which tracks touch movements
var drawer = {
    isDrawing: false,
    touchstart: function (coors) {
        context.beginPath();
        context.moveTo(coors.x, coors.y);
        this.isDrawing = true;
    },
    touchmove: function (coors) {
        if (this.isDrawing) {
            context.lineTo(coors.x, coors.y);
            context.stroke();
        }
    },
    touchend: function (coors) {
        if (this.isDrawing) {
            this.touchmove(coors);
            this.isDrawing = false;
        }
    }
};
// create a function to pass touch events and coordinates to drawer
function draw(event) { 
    var type = null;
    // map mouse events to touch events
    switch(event.type){
        case "mousedown":
                event.touches = [];
                event.touches[0] = { 
                    pageX: event.pageX,
                    pageY: event.pageY
                };
                type = "touchstart";                  
        break;
        case "mousemove":                
                event.touches = [];
                event.touches[0] = { 
                    pageX: event.pageX,
                    pageY: event.pageY
                };
                type = "touchmove";                
        break;
        case "mouseup":                
                event.touches = [];
                event.touches[0] = { 
                    pageX: event.pageX,
                    pageY: event.pageY
                };
                type = "touchend";
        break;
    }    

    // touchend clear the touches[0], so we need to use changedTouches[0]
    var coors;
    if(event.type === "touchend") {
        coors = {
            x: event.changedTouches[0].pageX,
            y: event.changedTouches[0].pageY
        };
    }
    else {
        // get the touch coordinates
        coors = {
            x: event.touches[0].pageX,
            y: event.touches[0].pageY
        };
    }
    type = type || event.type
    // pass the coordinates to the appropriate handler
    drawer[type](coors);
}

// detect touch capabilities
var touchAvailable = ('createTouch' in document) || ('ontouchstart' in window);

// attach the touchstart, touchmove, touchend event listeners.
if(touchAvailable){
    canvas.addEventListener('touchstart', draw, false);
    canvas.addEventListener('touchmove', draw, false);
    canvas.addEventListener('touchend', draw, false);        
}    
// attach the mousedown, mousemove, mouseup event listeners.
else {
    canvas.addEventListener('mousedown', draw, false);
    canvas.addEventListener('mousemove', draw, false);
    canvas.addEventListener('mouseup', draw, false);
}

// prevent elastic scrolling
document.body.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, false); // end body.onTouchMove

}, false); // end window.onLoad


function generate(){

var newCanvas = document.createElement('canvas');
newCanvas.width = 400;
newCanvas.height = 400;
document.getElementById('container').appendChild(newCanvas);
ctx = newCanvas.getContext('2d');
}

//]]>  

here is jsfiddle http://jsfiddle.net/regeme/WVUwn/ ps:drawing not displayed on jsfiddle however it works on my localhost I have totally no idea about it , anyway what I need is generate function , I did but I think I am missing something.. Any ideas? thanks..

3 Answers 3

1

Below is a function I wrote to dynamically create canvas.

If the canvas already exists (same ID) then that canvas is returned.

The pixelRatio parameter can be defaulted to 1. It's used for setting the correct size on retina displays (so for iPhone with Retina the value would be 2)

function createLayer(sizeW, sizeH, pixelRatio, id, zIndex) {

    // *** An id must be given.
    if (typeof id === undefined) {
        return false;
    }

    // *** If z-index is less than zero we'll make it a buffer image.
    isBuffer = (zIndex < 0) ? true : false;


    // *** If the canvas exist, clean it and just return that.
    var element = document.getElementById(id);
    if (element !== null) {
        return element;
    }

    // *** If no zIndex is passed in then default to 0.
    if (typeof zIndex === undefined || zIndex < 0) {
        zIndex = 0;
    }

    var canvas = document.createElement('canvas');

    canvas.width = sizeW;
    canvas.height = sizeH;
    canvas.id = id;
    canvas.style.width = sizeW*pixelRatio + "px";
    canvas.style.height = sizeH*pixelRatio + "px";
    canvas.style.position = "absolute";
    canvas.style.zIndex = zIndex;

    if (!isBuffer) {
        var body = document.getElementsByTagName("body")[0];
        body.appendChild(canvas);
    }

    return canvas;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change the jsfiddle option

"onLoad" 

to

"No Wrap - in <body>"

EDIT: See also similar question over here: Uncaught ReferenceError for a function defined in an onload function

JSFiddle options: http://doc.jsfiddle.net/basic/introduction.html#frameworks-and-extensions

3 Comments

I am sorry but what is this for?
hmm I am not worrying about jsfiddle my main question is about generate function to generate new canvases dynamically , not to sweat about jsfiddle , thanks anyway..
The question was: "I want to generate canvases dynamically". If you look at the console when running your code in JSFiddle, the function "generate()" is never called. By switching the JSFiddle option, you not only have a canvas appended to the document, but also a working drawing in the first canvas (and it will not work on the second one since it's not the same context that is used for the drawing calls).
0

This is the working update of your JSFIDDLE

javascript:

document.getElementById('generate').addEventListener('mousedown', generate, false);

I guess this is what you want.

I've just added an eventListener to your button in javascript code itself.

P.S.: I've also added black background color to canvas to show it on white background.

4 Comments

We both answer the question asked, however it's apparently not what he's looking for.
@Mr_Pouet I guess so. But the question says the same. Isn't it?
thank you both for your interest I appreciate that.. Now a new problem occured which is I can not draw the new generated canvas . I copy and paste the whole script into the generate function but it did not work.. What shuold I do , any recommendations?
This is a different question. Please create a new thread. (and if you feel like it, throw one or two up-votes around ;))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.