How to set the background image of a html 5 canvas to .png image

Farzad Towhidi picture Farzad Towhidi · Mar 9, 2011 · Viewed 149.6k times · Source

I would like to know how it is possible to set the background image of a canvas to a .png file. I do not want to add the image in the back of the canvas and make the canvas transparent.

I want the user to be able to actually draw on that canvas with the background being the .png image so that I can extract it later as a .png with the drawings that the user made.

Answer

Phrogz picture Phrogz · Mar 9, 2011

As shown in this example, you can apply a background to a canvas element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL().

Here are the contents of the example, for Stack Overflow posterity:

<!DOCTYPE HTML>
<html><head>
  <meta charset="utf-8">
  <title>Canvas Background through CSS</title>
  <style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(lotsalasers.jpg) }
  </style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  ctx.strokeRect(140,60,40,40);
  var img = document.getElementsByTagName('img')[0];
  img.src = can.toDataURL();
</script>
</body></html>