为什么我收到错误" Uncaught SecurityError:无法执行' toDataURL' on' HTMLCanvasElement':可能无法导出受污染的画布。 "

时间:2014-07-02 13:08:54

标签: javascript

我已经查看了其他问题,但仍然无法得出答案。

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

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中使用的图像

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

只需使用crossOrigin属性

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