简体   繁体   English

使用toDataURL(“image / png”)时如何捕获HTML5 Canvas的背景?

[英]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. 这是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. 但是,当我点击“ Create Collage按钮时,背景是透明的。 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. 我已经提到了类似的问题,发现我们可以使用或将Canvas放在上面。 I'm not getting how can I implement that and when I will click on Create Collage button, its gonna capture the background? 我没有得到如何实现它,当我点击Create Collage按钮时,它会捕获背景? I'm not sure about it. 我不确定。 I'm using Fabric.js Thanks for any help. 我正在使用Fabric.js感谢您的帮助。

You can't! 你不能! CSS backgrounds are not part of the canvas (just the element as any background to other elements). CSS背景不是画布的一部分(只是元素作为其他元素的任何背景)。

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() . 您需要将背景绘制到画布上,而不是将其用作CSS背景,因为这是toDataURL()捕获的唯一数据。

If you are using clearRect or fillRect to update the canvas you can consider using drawImage instead with the background image. 如果使用clearRectfillRect更新画布,则可以考虑使用drawImage而不是背景图像。

Better to use html2canvas script. 最好使用html2canvas脚本。

The code look like this. 代码看起来像这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM