【问题标题】:canvas.toDataURL() doesn't return image [duplicate]canvas.toDataURL() 不返回图像[重复]
【发布时间】:2015-10-13 17:33:03
【问题描述】:

我希望返回图像 Mirror-ed,它返回黑色图像。

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      margin: 0px;
      padding: 0px;
    }
  </style>
</head>

<body>
  <img id="canvasImg" alt="Right click to save me!">
  <!--PLACE WHERE IMAGE MUST BE PUT ANFTER MIRROR-->
  <canvas id="myCanvas" width="1000" height="1000" style="background:#0094ff"></canvas>
  <!--Canvas Element-->
  <script>
    /*Creating Canvas*/
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

     // translate context to center of canvas
    context.translate(canvas.width / 2, canvas.height / 2);
    /*center the image*/

     // flip context horizontally
    context.scale(-1, 1); /*mirror image*/


    var imageObj = new Image();
    /*creating image object*/
    imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

    imageObj.onload = function() {

      context.drawImage(imageObj, -imageObj.width / 2, -imageObj.height / 2);
      /* draw and center the image*/
      context.restore();
      context.save();
    };
    var dataURL = canvas.toDataURL("image/jpeg");
    /* canvas to url  */
    document.getElementById('canvasImg').src = dataURL;
     // using url as source for img with id canvasImg
  </script>
</body>

</html>

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    这里主要有两个问题。

    1.) 您甚至在画布绘制之前就将画布转换为 dataURL。 添加延迟以查看结果。

    setTimeout(function(){
              var dataURL = canvas.toDataURL("image/jpeg");
              console.log(dataURL);
              /* canvas to url  */
              document.getElementById('canvasImg').src = dataURL;
               // using url as source for img with id canvasImg
        },2000);
    

    2.) 您正在从不同的服务器加载图像,因此会引发安全问题。在控制台中查看错误。 “未捕获的 SecurityError:无法在 'HTMLCanvasElement' 上执行 'toDataURL':可能无法导出受污染的画布。”

    现在,为避免此错误,您可以将图像下载到本地计算机。将图像路径更改为将图像存储在本地计算机上的位置。这将起作用。

    【讨论】:

    • 正确的位置应该是在load 回调中,而不是在超时中。
    • 非常感谢它成功了! :)
    • 是的。您也可以使用 .complete 属性,但它可能不适用于所有浏览器(特别是 firefox)。
    • 更正:您可以从任何您想要的服务器传送图像,只要该服务器与网页位于同一域中。
    猜你喜欢
    • 2019-06-21
    • 2014-03-27
    • 2015-02-23
    • 1970-01-01
    • 2021-06-30
    • 2015-07-16
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多