Say I have a index.html with a canvas in it:
<html>
<head>
</head>
<body style="text-align: center;background: #f2f6f8;">
<div style="display:inline-block;width:auto; margin: 0 auto; background: black; position:relative; border:5px solid black; border-radius: 10px; box-shadow: 0 5px 50px #333">
<canvas id="gameCanvas" width="320" height="480"></canvas>
</div>
</body>
</html>
and the canvas is showing ok this way ~~~
Now I want to put a image as background behind the canvas and I tried to add a img tag in the body:
<html>
<head>
</head>
<body style="text-align: center;background: #f2f6f8;">
<img src="xxx.png" alt="" />
<div style="display:inline-block;width:auto; margin: 0 auto; background: black; position:relative; border:5px solid black; border-radius: 10px; box-shadow: 0 5px 50px #333">
<canvas id="gameCanvas" width="320" height="480"></canvas>
</div>
</body>
</html>
but then the canvas appeared to show after the image not on top of it ...
I really know nothing about html I think it should not be that hard to get this done, hope someone can give a hand here, thanks :)
To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.
There are two ways available in FabricJS, using which we can change the background image of the canvas. First method is by using the Canvas class itself and passing backgroundImage in the second parameter of the class. Second method is to use the setBackgroundColor method.
Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .
Live Demo
You just need to use z-index
. I put the image and the canvas element in a container, and position them so the canvas will always be over the image.
Also another note, you shouldn't size your canvas using CSS, you should always do it via the properties directly. In my fiddle I did it via JS.
<div id="container">
<img class='img' src="http://lorempixel.com/320/480/" alt="" />
<canvas id="gameCanvas" width="320" height="480"></canvas>
</div>
body{text-align: center;background: #f2f6f8;}
.img{position:absolute;z-index:1;}
#container{
display:inline-block;
width:320px;
height:480px;
margin: 0 auto;
background: black;
position:relative;
border:5px solid black;
border-radius: 10px;
box-shadow: 0 5px 50px #333}
#gameCanvas{
position:relative;
z-index:20;
}
you can draw image in canvas like this , rather than putting canvas
on image
var topMap = new Image();
topMap.src = "myiamge.jpeg";
function drawMap() {
context.clearRect(0, 0, WIDTH, HEIGHT);
context.drawImage(topMap, 0, 0);
}
function init() {
drawMap();
}
topMap.onload = function() {
init();
}
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