4

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');
    });
});
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Imgur has cors enabled afaik
@rlemon - they probably do, but I got the "canvas tainted by cross-origin ... " error in my console, so I just replaced the images with Base64 for the fiddle ?
+1 in canvas, can we allow to move balloon where ever we click inside the canvas only ?
You can move the baloon where ever you like, this just saves whatever is in the canvas at the time, and I just conveniently choose to use the same button for saving. You can have another button, hook into a click event on the canvas, or whatever really.

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.