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.
This question is related to
html
canvas
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>
You can give the background image in css :
#canvas { background:url(example.jpg) }
it will show you canvas back ground image
You can use this plugin, but for printing purpose i have added some code like
<button onclick="window.print();">Print</button>
and for saving image <button onclick="savePhoto();">Save Picture</button>
function savePhoto() {
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
window.location = img;}
checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app
You can draw the image on the canvas and let the user draw on top of that.
The drawImage()
function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images
Source: Stackoverflow.com