G
G
genesis11112020-12-21 19:54:56
JavaScript
genesis1111, 2020-12-21 19:54:56

How to save canvas to jpg given the use of drawImage?

If you use the code as is, it saves an empty area. If, for example, a line is drawn before saving, an empty area with a line, without a picture, will be saved. Looks good in the browser.
PS
Tried on a hosting with a link to img url (from the same hosting-domain) the result is the same.

function draw() {
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, 0, 114, 600, 486);
    };
  img.src = "file:///C:/Users/1/Desktop/1.jpg";
      
  
  var link = document.getElementById('link');
  link.setAttribute('download', 'MintyPaper.jpg');
  link.setAttribute('href', canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream"));
    }

<body onload="draw();">
  <canvas id="myCanvas" width="600" height="600"></canvas>
  <a id="link">SAVE</a>
</body>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2020-12-21
@genezis1111

I see two possible reasons why it doesn't work.
1. The current document and the picture have a different source, i.e. the protocol / address / port does not match
2. The picture does not have time to load, you need to wait a bit so as not to get a void

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question