简体   繁体   中英

canvas + drawImage, toDataURL returns blank image

The problem of genres when I am adding image to canvas (drawImage), when I draw a drawing with the other canvas methods I have no problems.

var ready;
ready = function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();

imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

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

var pngUrl = canvas.toDataURL();
console.log(pngUrl);
$('#client_avatar').val(pngUrl);

};

before setting source you must define onload otherwise it will not be able to call onload.

$(document).ready(function() {
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var imageObj = new Image();


    imageObj.onload = function() {
      context.drawImage(imageObj, 69, 50);
    };
    imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';


    var pngUrl = canvas.toDataURL();
    console.log(pngUrl);
//    $('#client_avatar').val(pngUrl);
$("#client_avatar").append("<img src='"+ pngUrl +"'>")

    });

Here is working jsbin link

 $(document).ready(function() { var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.onload = function() { context.drawImage(imageObj, 0, 0, 200, 200); var pngUrl = canvas.toDataURL(); console.log(pngUrl); $('#client_avatar').attr('src', pngUrl); }; imageObj.crossOrigin = 'anonymous'; //not necessary, if image hosted on same server imageObj.src = 'https://i.imgur.com/Q6aZlme.jpg'; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas id="canvas" width="200" height="200"></canvas> <img id="client_avatar"> 

apology for not giving any explanation

ʜᴀᴠᴇ ꜰᴜɴ :)

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