Save Canvas with Background Image
10,048
Solution 1
To save an image location, I believe your looking for:
window.location = canvas.canvas.toDataURL('image/png');
The first canvas call is your variable the second is the canvas object. You should probably rename your variable to something unique.
To set an image in canvas and make that the background requires some more work:
var myCanvas = document.querySelector('myCanvas'),
img = document.createElement('img'),
ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null;
myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;
img.onload = function () {
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
};
img.src = 'image.png';
updated to redraw the image.
Solution 2
When you want to save the Canvas + background as an image, you will need to do a sequence of events:
- Create an in-memory canvas just as big as your normal canvas. Call it can2
ctx2.drawImage(can1, 0, 0)
// paint first canvas onto new canvasctx.clearRect(0, 0, width, height)
// clear first canvasctx.drawImage(background, 0, 0)
// draw image on first canvasctx.drawImage(can2, 0, 0)
// draw the (saved) first canvas back to itself
Author by
Akash
Tell me and i forget. Teach me and i remember. Involve me and i learn. - Benjamin Franklin
Updated on June 15, 2022Comments
-
Akash almost 2 years
I have a background image for a canvas, and added a few basic elements to the canvas. Now I want to save the canvas (in .png), with the background image of the canvas style.
Tried:
var canvas = document.getElementById("mycanvas"); var img = canvas.toDataURL("image/png");
But this doesn't seem to save the background image of the canvas. Is there a way out?
-
anam over 10 yearscan you plz explain more ?? i need this functionality
-
Jose Manuel Abarca Rodríguez almost 5 yearsI get an error in "myCanvas.canvas.toDataURL" : the "canvas" is undefined.
-
Jose Manuel Abarca Rodríguez almost 5 yearsSimon, would explain your idea just a little bit? We really need it :)