Search code examples
javascriptcanvascreatejseaseljs

How to get all the points that are drawn on the canvas and store it in a database using EaselJS?


Is it possible to get all the points that are drawn on the canvas using EaselJS and store it in a database so that I can reload it for later use? I'm trying to make a load and edit version of this code: `https://jsfiddle.net/lannymcnie/ZNYPD/, can anyone help me?

var stage = new createjs.Stage("canvas");
createjs.Ticker.addEventListener("tick", stage);

// Add some text to draw on top of (also instructions)
stage.addChild(new createjs.Text("Click and Drag to Draw", "40px Arial", "#000000").set({x:200,y:200}));

// Set up the container. We use it to draw in, and also to get mouse events.
var wrapper = new createjs.Container();
wrapper.hitArea = new createjs.Shape(new createjs.Graphics().f("#000").dr(0,0,800,600));
wrapper.cache(0,0,800,600); // Cache it.
stage.addChild(wrapper);

// Create the shape to draw into
var drawing = new createjs.Shape();
wrapper.addChild(drawing);

var lastPoint = new createjs.Point();

wrapper.addEventListener("mousedown", function(event) {

    // Store the position. We have to do this because we clear the graphics later.
    lastPoint.x = event.stageX;
    lastPoint.y = event.stageY;

    // Listen for mousemove
    event.addEventListener("mousemove", function(event){

        // Draw a round line from the last position to the current one.
        drawing.graphics.ss(20, "round").s("#ff0000");
        drawing.graphics.mt(lastPoint.x, lastPoint.y);        
        drawing.graphics.lt(event.stageX, event.stageY);

        // Update the last position for next move.
        lastPoint.x = event.stageX;
        lastPoint.y = event.stageY;

        // Draw onto the canvas, and then update the container cache.
        var erase = document.getElementById("toggle").checked;
        wrapper.updateCache(erase?"destination-out":"source-over");
        drawing.graphics.clear();
    });
});

Solution

  • You can obviously store each individual stageX and stageY, but we are talking about very large amount of coordinate pairs and also it can be tricky redraw everything from scratch by "parsing" these coordinates.

    I would suggest a different approach for this. How about saving the drawing as an image file, storing it to the server, and then load it up at a later time on the canvas, like this:

    //save canvas to image for latter use
    image.src = canvas.toDataURL('image/jpeg');
    
    //load the image on a clean canvas
    var stage = new createjs.Stage(canvas);
    var bitmap = new createjs.Bitmap(image);
    stage.addChild(bitmap);
    stage.update();
    

    After this, your canvas should look exactly as before, and you can start drawing again on top of it, after all of your listener functions have been re-initialized.