Chamaququm
Chamaququm

Reputation: 6728

Save multiple images in canvas JQuery

Can we save the image in canvas. Like as shown in the JSFiddle.

I want to save the image in such a way the balloon should come over the image

$(document).ready(function() {
    var d_canvas = document.getElementById('canvas');
    var context = d_canvas.getContext('2d');
    var background = document.getElementById('background');
    var ballon = document.getElementById('ballon')
    context.drawImage(background, 0, 0);

    $('#ballon').draggable();

    $('#draw').click(function() {
        var $ballon = $('#ballon'),
            $canvas = $('#canvas');
        var ballon_x = $ballon.offset().left - $canvas.offset().left,
            ballon_y = $ballon.offset().top - $canvas.offset().top;

        context.drawImage(ballon, ballon_x, ballon_y);

        $ballon.hide();
        $(this).attr('disabled', 'disabled');
    });
});

Upvotes: 4

Views: 1347

Answers (1)

adeneo
adeneo

Reputation: 318182

There are generally two ways to get an image from a canvas:

  1. using getImageData() to get the rgba value for every pixel for a given rectangle of the canvas.

  2. using toDataURL() to get a Base64 string of the entire canvas.

The second method is probably most useful, and combined with some HTML5 magic, and the download attribute, we can create a downloadable image or send the string to the server and save it as an image :

var base64 = d_canvas.toDataURL("image/png");

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

a.href        = base64,
a.target      = '_blank';
a.download    = 'myImage.png';

document.body.appendChild(a);
a.click();

If you need the baloon to be in a specific place, moving that should be trivial.

Here's a

FIDDLE

Note that I had to remove the external images and use base64 to avoid cross-origin images in the canvas.

Upvotes: 3

Related Questions