使用JS Jquery下载画布图像 [英] Download canvas image using JS Jquery

查看:129
本文介绍了使用JS Jquery下载画布图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码将画布图像下载到桌面:

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:

未捕获的TypeError:无法读取未定义的属性'toDataURL'

Uncaught TypeError: Cannot read property 'toDataURL' of undefined

有没有人知道如何解决此问题?

Does anyone have a idea how to fix this?

现场预览: http:/ /dane.helpful.ninja/fds/index.php?username=z-justin

介绍:1)点击图片2)查看Dev控制台

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

EDIT:

将代码更新为以下内容后:

After updating the code to the following:

在全局范围内定义画布从中删除​​ var var canvas = $(this).find canvas')[0];

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

弹出以下错误:

未捕获的SecurityError:无法在'HTMLCanvasElement'上执行'toDataURL':无法导出已污染的画布。

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

推荐答案

使用canvas变量从回调到ready方法,因为此方法被执行并且canvas变量的作用域将被终止。当调用点击回调时,不会有任何canvas变量实例,因为它已经结束。

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>

这篇关于使用JS Jquery下载画布图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆