Canvas How to - Draw an image








Question

We would like to know how to draw an image.

Answer


<!-- w w  w.j  a  v  a 2  s .co  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('my_canvas');
  var ctx = canvas.getContext('2d');
  var imageObj = new Image();
  ctx.canvas.width = 100;
  ctx.canvas.height = 100;
  imageObj.onload = function() {
     ctx.drawImage(imageObj, 0, 0,100,100);
  };
  imageObj.src = 'http://www.java2s.com/style/download.png';
}
</script>
</head>
<body>
  <canvas id="my_canvas"></canvas>
</body>
</html>

The code above is rendered as follows: