Skip to content Skip to sidebar Skip to footer

How To Combine 3 Canvas Html Elements Into 1 Image File Using Javascript/jquery?

I have 3 canvas i.e. canvasTarget, canvasTarget2, canvasTarget3 as shown below: var canvas = document.getElementById('canvasTarget'); var img = canvas.toDataURL('im

Solution 1:

So you've rendered your canvases, but it's not clear how you want to combine them - overlaid, side-by-side? In either case you can use Canvas.context.drawImage() to add them to a new canvas object, and then use the Canvas.toDataURL() method to return the, erm, dataURL of the new canvas.

Something like this perhaps...

/* assumes each canvas has the same dimensions */var overlayCanvases = function(cnv1, cnv2, cnv3) {
    var newCanvas = document.createElement('canvas'),
        ctx = newCanvas.getContext('2d'),
        width = cnv1.width,
        height = cnv1.height;

    newCanvas.width = width;
    newCanvas.height = height;

    [cnv1, cnv2, cnv3].forEach(function(n) {
        ctx.beginPath();
        ctx.drawImage(n, 0, 0, width, height);
    });

    return newCanvas.toDataURL();
};

/* assumes each canvas has the same width */var verticalCanvases = function(cnv1, cnv2, cnv3) {
    var newCanvas = document.createElement('canvas'),
        ctx = newCanvas.getContext('2d'),
        width = cnv1.width,
        height = cnv1.height + cnv2.height + cnv3.height;

    newCanvas.width = width;
    newCanvas.height = height;

    [{
        cnv: cnv1,
        y: 0
    },
    {
        cnv: cnv2,
        y: cnv1.height
    },
    {
        cnv: cnv3,
        y: cnv1.height + cnv2.height
    }].forEach(function(n) {
        ctx.beginPath();
        ctx.drawImage(n.cnv, 0, n.y, width, n.cnv.height);
    });

    return newCanvas.toDataURL();
};

/* USAGE */var dURL1 = overlayCanvases(canvas1,canvas2,canvas3);
var dURL2 = verticalCanvases(canvas1,canvas2,canvas3);

The overlayCanvases() function will place the canvases on top of each other, so the order of the arguments is important. The verticalCanvases() will align the canvas vertically and in descending order. The important thing to notice here is that Canvas.context.drawImage() allows you to paint one canvas into another - relative positioning can be jiggled to suit your purposes.

Functions above Fiddled : https://jsfiddle.net/BnPck/cyLrmpjy/

Post a Comment for "How To Combine 3 Canvas Html Elements Into 1 Image File Using Javascript/jquery?"