How can I capture the background of HTML5 Canvas when using toDataURL (& ldquo; image / png & rdquo;)?

advertisements

I'm creating a collage making application.

This is the code of Canvas. The image is appearing in the background of canvas.

<canvas id="c" width="800" height="600" style="left: -300px; background-image: url('_include/img/Images/rainy_day-1366x768.jpg');"></canvas>

But, when I click on Create Collage button the background is transparent. How can I capture the canvas with background image?

Button click code:

function convertCanvasToImage() {
                    var canvas = document.getElementById('c');
                    var image_src = canvas.toDataURL("image/jpeg");
                    window.open(image_src);
                }

I've referred the similar questions and found that we can use or and place Canvas over it. I'm not getting how can I implement that and when I will click on Create Collage button, its gonna capture the background? I'm not sure about it. I'm using Fabric.js Thanks for any help.


You can't! CSS backgrounds are not part of the canvas (just the element as any background to other elements).

You you need to draw the background onto the canvas instead of using it as a CSS background as this is the only data captured by toDataURL().

If you are using clearRect or fillRect to update the canvas you can consider using drawImage instead with the background image.