javascript - Missing image when saving image from canvas -


i use code save images in javascript :

function saveimage() {     var canvas = document.getelementbyid('mypicture');     var ctx = canvas.getcontext('2d');     var img = new image();     ctx.rect(0, 0, 460, 600);     ctx.fillstyle = 'white';     img = new image();     img.crossorigin = 'anonymous';     img.src = "http://localhost/upload/abc.jpg";     ctx.drawimage(img,0,0,_item.width(),_item.height());     return canvas.todataurl("image/jpeg"); } 

when click button save image:

$("#save").on('click', function () {     var rawimagedata = saveimage();     $(this).attr('download', 'your_pic_name.jpeg').attr('href', rawimagedata); }); 

however result white image. , click on save button again (ie 2 times) right result. how can click 1 time only? thank you.

it because first time click, anchor doesn't have image data url... may set url , forget click event.

  //$("#save").on('click', function () {     var rawimagedata = saveimage();    $(this).attr('download', 'your_pic_name.jpeg')           .attr('href', rawimagedata);   //}); 

or

  $("#save").on('click', function () {     var rawimagedata = saveimage();    /*$(this).attr('download', 'your_pic_name.jpeg')           .attr('href', rawimagedata);*/         window.location=rawimagedata;   }); 

or alternatively, need this file use following code

   var canvas = document.getelementbyid('mypicture');  function saveimage() {    var ctx = canvas.getcontext('2d');    var img = new image();    ctx.rect(0, 0, 460, 600);    ctx.fillstyle = 'white';    img = new image();    img.crossorigin = 'anonymous';    img.src = "http://localhost/upload/abc.jpg";    //  ctx.fill...    return canvas.todataurl("image/jpeg"); }   $("#save").on('click', function () {     var rawimagedata = saveimage();     var png= canvas2image.saveaspng(canvas , true);   }); 

ps: don't see feel canvas image...int saveimage function


Comments