HTML5 canvas draw image examples

HTML5 canvas draw image examples using drawImage().

Using image from html

<img id="img1" src="/img/elephant1_small.jpg">
<canvas id="canvas1" width="200" height="100" style="background-color:lightgray;"></canvas>
<script type="text/javascript">
window.addEventListener("load", draw);
function draw() {
  var canvas = document.querySelector('#canvas1');
  var ctx = canvas.getContext('2d');
  var img1 = document.querySelector("#img1");
  ctx.drawImage(img1, 20, 10);
}
</script>
refresh

Using javascript Img object

<canvas id="canvas1" width="200" height="100" style="background-color:lightgray;"></canvas>
<script type="text/javascript">
window.addEventListener("load", draw);
function draw() {
  var canvas = document.querySelector('#canvas1');
  var ctx = canvas.getContext('2d');
  var img1 = new Image();
  img1.onload = function() {ctx.drawImage(img1, 40, 10);}
  img1.src = "/img/elephant1_small.jpg";
}
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments