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?
There are two ways available in FabricJS, using which we can change the background image of the canvas. First method is by using the Canvas class itself and passing backgroundImage in the second parameter of the class. Second method is to use the setBackgroundColor method. Let's see into each of them with an example.
Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.
When you want to save the Canvas + background as an image, you will need to do a sequence of events:
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 itselfTo 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With