0

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.

d4nex
  • 55
  • 1
  • 8

1 Answers1

0

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>
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
  • Getting the following error now: Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. Any idea? – d4nex Sep 21 '15 at 10:50
  • For that error, This http://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror question might help you. – Laxmikant Dange Sep 21 '15 at 10:51