Blank PNG / Tainted canvases may not be exported (not using images)

左心房为你撑大大i 提交于 2019-12-02 04:10:25

问题


I am trying to export a fairly simple html to canvas and then png. To do so, I am using rasterizeHTML (http://cburgmer.github.io/rasterizeHTML.js/). The problem that I am facing is that I get a warning like if I was loading an external image/resource, but I am not. This is what I have tried:

HTML:

<canvas height="500" width="500" id="rasterizer"></canvas>

Javascript

var canvas=document.getElementById("rasterizer");
rasterizeHTML.drawHTML('<div width="300px" height="300px" > <div style="width: 200px;height: 200px;position: absolute;top: 50%;left: 50%;margin: -100px 0 0 -100px;"><div style="width: 100%;height: 100%;border-radius: 50%;position: absolute;top: 0;left: 0;margin: 0;z-index: 1;background: #e4f1ea; ">            </div>            <div style="border-radius: 50%;position: absolute;top: 50%;left: 50%;z-index: 3;background: #b6cfe1;width:73.997475122531%; height:73.997475122531%; margin:-36.998737561265% 0 0 -36.998737561265%"></div>        </div></div>',canvas);
canvas.toDataURL("image/png");

The html just renders 2 circles, one above the other. Rasterizer is able to show this in the canvas with no problem, but then when I try to run .toDataURL I end up with one of two issues:

  1. A blank image (if it is the first time I run the code) the same size as the canvas.
  2. SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.

I am out of ideas, since this should happen with external resources, not with fully inline-d html. Anyone know why this could happen? Thanks.


回答1:


There are two things at work here:

  1. You should wait for rasterizeHTML.drawHTML to finish before expecting anything from the canvas:

    
    rasterizeHTML.drawHTML('<div...', canvas, function () {
        var dataUrl = canvas.toDataURL("image/png");
        console.log(dataUrl);
    });
    
  2. Safari & Webkit cannot read back from the canvas once HTML (actually a SVG) has been drawn there. See https://github.com/cburgmer/rasterizeHTML.js/wiki/Browser-issues#wiki-webkit. A bug has been filed with both Chrome and Safari (again, see the link), but until then Firefox sadly is the only browser that allows you to read form it.



来源:https://stackoverflow.com/questions/21093199/blank-png-tainted-canvases-may-not-be-exported-not-using-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!