为什么我得到错误“Uncaught SecurityError: Failed to execute 'toDa

Why am I getting the error "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. "

本文关键字:execute to Failed toDa SecurityError 错误 Uncaught 为什么      更新时间:2023-09-26

我已经看了其他问题,但仍然想不出答案。

当用户点击"保存项目"按钮时,此功能被触发:

function common_save_project()
{
  var image = common_screenshot();
}

调用common_screen ()

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使用

您正在从本地文件系统加载文件,而不是使用本地主机请求。

通过本地主机文件服务器运行应用程序,并确保仅通过http://加载应用程序中的文件,而不是从本地系统加载文件。(即c:/或file://或/usr)

使用crossOrigin属性

var image= new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = url;