Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 204
Farzad Towhidi Avatar asked Mar 09 '11 04:03

Farzad Towhidi


People also ask

How do you put a PNG image as a background in HTML?

background-image: url('myimage. png'); Change myimage. png to the location of your image.

Can PNG be used as background HTML?

To set the background image of a webpage, use the CSS style. Under the CSS <style> tag, add the property background-image. The property sets a graphic such as jpg, png, svg, gif, etc. HTML5 do not support the <body> background attribute, so CSS is used to change set background image.


1 Answers

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> 
like image 184
Phrogz Avatar answered Sep 30 '22 16:09

Phrogz