【发布时间】:2017-01-02 01:56:16
【问题描述】:
我有一个 HTML5 画布,我在其上从 svg 绘制图像。
HTML
<canvas id="canvas" width="600" height="320"></canvas>
JavaScript
var DOMURL = window.URL || window.webkitURL || window;
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="320">'+
'<foreignObject width="100%" height="100%">'+
'<style>'+
'foreignObject {'+
'background-color: #000;'+
'color: #fff'+
'border-radius: 10px;'+
'}'+
'h1 {'+
'color: #2acabd;'+
'font: 25px arial;'+
'font-weight: bold;'+
'text-align: center;'+
'}'+
'h2 {'+
'margin: 0;'+
'color: #2acabd;'+
'font: 15px arial;'+
'}'+
'p {'+
'color: #fff;'+
'}'+
'</style>'+
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size: 40px;">'+
'<h1>Heading</h1>'+
'<div>'+
'<div id="details-wrapper">'+
'<h2>Full Name</h2>'+
'<p>Alan Johnson</p>'+
'<h2>Date of Birth</h2>'+
'<p>7th November 1988</p>'+
'<p><span id="user-id">34329483028493284093284432</span></p>'+
'</div>'+
'</div>'+
'</div>'+
'</foreignObject>'+
'</svg>';
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
img = new Image();
img.setAttribute("crossOrigin", "anonymous");
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
console.log(canvas.toDataURL());
}
img.src = url;
(JS 小提琴:https://jsfiddle.net/LondonAppDev/qnpcg8th/1/)
当我打电话给canvas.toDataURL() 时,我得到了异常:
(index):98 Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
我在 Stack Overflow 上看到了许多其他与此异常相关的问题和答案。我的问题不同,因为(如您所见)我在任何时候都不会在我的 svg 或画布中包含来自另一个域的任何图像。
我猜问题是我正在使用DOMURL.createObjectURL 创建一个对象 URL。
我知道在不同的浏览器中执行此操作存在一些兼容性问题,但是此应用只需要在 Chrome 中运行。另外,不能直接在画布上绘制文本,我必须通过 svg 来完成。
关于如何解决此问题并成功获取我的画布的 PNG 的任何想法?
【问题讨论】:
-
您是否尝试过使用数据 url 而不是
createObjectURL?
标签: javascript html canvas svg