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.
background-image: url('myimage. png'); Change myimage. png to the location of your image.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With