Prateek Saini
Prateek Saini

Reputation: 173

How can I capture the background of HTML5 Canvas when using toDataURL("image/png")?

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.

Upvotes: 1

Views: 1127

Answers (2)

user1693593
user1693593

Reputation:

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.

Upvotes: 5

Arunkumar Vasudevan
Arunkumar Vasudevan

Reputation: 5330

Better to use html2canvas script.

The code look like this.

html2canvas($("#c"), {
    onrendered: function(canvas) {
        var Image1 = canvas.toDataURL("image/jpeg");
        window.open(Image1);
    }

Upvotes: -1

Related Questions