Download canvas image using JS Jquery

点点圈 提交于 2019-12-25 06:09:18

问题


I'm trying to download a canvas image to the desktop using the following code:

<script type="text/javascript">
    var canvas;
    $(document).ready(function() {
      if ($('#designs-wrapper').length) {
        $('.design').each(function() {
          var design = $(this).attr('data-design');
          var canvas = $(this).find('canvas')[0];
          var ctx = canvas.getContext('2d');
          var img = new Image;
          img.onload = function() {
            ctx.drawImage(this, 0, 0);
          };
          img.src = design;
        });
      }

      $('#canvas').click(function() {
        this.href = canvas.toDataURL();
        this.download = 'design.png';
      });

    });
</script>

Sadly I'm getting the following error:

Uncaught TypeError: Cannot read property 'toDataURL' of undefined

Does anyone have a idea how to fix this?

Live preview: http://dane.helpful.ninja/fds/index.php?username=z-justin

Introductions: 1) Click a image 2) See Dev console

EDIT:

After updating the code to the following:

Define canvas in global-scope Remove var from var canvas = $(this).find('canvas')[0];

The following error pops up:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.


回答1:


You can't use canvas variable from call back to ready method as this method gets executed and scope of canvas variable will gets ended. When you call click callback, there will not be any instance of canvas variable as it is already ended.

<script type="text/javascript">
    var canvas;
    $(document).ready(function() {
      if ($('#designs-wrapper').length) {
        $('.design').each(function() {
          var design = $(this).attr('data-design');
          var canvas = $(this).find('canvas')[0];
          var ctx = canvas.getContext('2d');
          var img = new Image;
          img.onload = function() {
            ctx.drawImage(this, 0, 0);
          };
          img.src = design;
        });
      }

      $('#canvas').click(function() {
        this.href = $('#canvas')[0].toDataURL();// Change here
        this.download = 'design.png';
      });

    });
</script>


来源:https://stackoverflow.com/questions/32693210/download-canvas-image-using-js-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!