1

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);

};

  • You should also add the jQuery tag to your question since you're using that library in your source code. – NewToJS Jun 16 '17 at 00:27
  • use this line `imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';` aftere onload callback – owais Jun 16 '17 at 00:28
  • I moved the line and still showing a blank image :/ – Carlos Ignacio Gomez Maureira Jun 16 '17 at 00:40
  • You have to call toDataURL inside your image's `onload` handler. This handler will be called asynchronously (i.e after the execution of the current stream of js), and thus at the time you call `toDataURL`, nothing has been drawn on the canvas yet. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Kaiido Jun 16 '17 at 01:48
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kaiido Jun 16 '17 at 01:48

2 Answers2

1

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

owais
  • 4,752
  • 5
  • 31
  • 41
0

$(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

ʜᴀᴠᴇ ꜰᴜɴ :)

ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110