我已經看過其他問題,但仍不能提出答案。爲什麼我會在'HTMLCanvasElement'上得到錯誤「Uncaught SecurityError:未能執行'toDataURL':受污染的畫布可能無法導出。」
當用戶點擊「保存項目」按鈕,這個功能被激發:
function common_save_project()
{
var image = common_screenshot();
}
這就要求common_screenshot()
function common_screenshot()
{
var canvas = document.getElementById("save_image_canvas");
var ctx = canvas.getContext('2d');
if (typeof(moulding_canvas) === "undefined")
{
canvas.height = parseInt($("#matte_canvas").height());
canvas.width = parseInt($("#matte_canvas").width());
}
else
{
canvas.height = parseInt($("#moulding_canvas").height());
canvas.width = parseInt($("#moulding_canvas").width());
}
canvas.style.backgroundColor = "#FFFFFF";
var moulding_top = 0;
var moulding_left = 0;
if (document.getElementById("moulding_canvas"))
{
moulding_top = -1 * parseInt(document.getElementById("moulding_canvas").style.top);
moulding_left = -1 * parseInt(document.getElementById("moulding_canvas").style.left);
}
var mattes_html = document.getElementById("mattes").innerHTML;
mattes_html = mattes_html.replace(/<\/?script\b.*?>/g, "");
mattes_html = mattes_html.replace(/ on\w+=".*?"/g, "");
console.log(mattes_html);
rasterizeHTML.drawHTML(mattes_html).then(function (renderResult)
{
ctx.drawImage(renderResult.image, moulding_left, moulding_top);
});
ctx.drawImage(matte_canvas, moulding_left, moulding_top);
if (typeof(moulding_canvas) !== "undefined")
{
ctx.drawImage(moulding_canvas, 0, 0);
}
//var image = new Image();
//image.src = canvas.toDataURL("image/jpeg");
//return image;
}
然後生成一個新的畫布,在它旁邊是一個測試按鈕。當被點擊:
function common_test()
{
var canvas = document.getElementById("save_image_canvas");
var image = new Image();
image.setAttribute('crossOrigin','anonymous');
image.src = canvas.toDataURL("image/jpeg");
$.ajax
(
{
type: "POST",
processData: false,
url: SITE_URL + "/system/xml/import/" + app_type + "/" + session_id + "/?prjid=" + project_id,
data: "xml=" + common_order_xml + "&prodid=" + product_id + "&file=" + image.src
}
).done(function(msg)
{
console.log("Project saved. " + msg);
});
}
然而,當我點擊該按鈕,我得到的錯誤:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
編輯:看來,錯誤發生時,我有以下幾點:
rasterizeHTML.drawHTML(mattes_html).then(function (renderResult)
{
ctx.drawImage(renderResult.image, moulding_left, moulding_top);
});
是否有另一種解決方案,我可以用來將html標記轉換爲圖像,然後我可以使用canvas.toURL
我不使用本地主機。我正在使用一個實際的域名。 – AllisonC
然後你有跨域問題。 出於安全原因,畫布將禁止從不同域加載的資產。 – Rodik
我的所有圖片都來自同一個域名。我不請求任何來自不同域的任何內容。 – AllisonC