문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top