简体   繁体   中英

image url to canvas and save

I am trying to load an image from a URL to the canvas, and then display the image to be saved. I can display the image in the canvas but when I trying to display the image as a base64 string it it blank. Here is what I can come up with so far just need help on the last part.

var canvas = document.getElementById('myCanvas'),
    context = canvas.getContext('2d'),
    imageObj = new Image();

imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
};

imageObj.src = 'http://3.bp.blogspot.com/-4NP3xwj-ZMI/UXU8RT1k02I/AAAAAAAACEU/88knXDu2MeQ/s72-c/music3g1.JPG';

var dataURL = canvas.toDataURL();
document.getElementById('canvasImg').src = dataURL;

Okay, a couple of things to know.

  1. When you draw an image to a canvas from a source outside of the domain the html is in, it flags the dirty flag on the canvas. This makes it so you can't use the .toDataURL() function. It is mainly a security issue.

  2. var dataURL = canvas.toDataURL(); document.getElementById('canvasImg').src = dataURL; is called before the image is actually drawn to the canvas. You'll need to get the data url and set the src within the onload function of the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM