Reputation: 189
I have 2 different codes using HTML5 canvas. I want to be able to layer the two together. I want the video to appear in the background of the animated square. Is there a way to do that in HTML5 Canvas?
square animation:
<canvas id="ex1" width="525" height="200" style="border: 5px solid black;" ></canvas>
<p id="text"> Increase/Decrease Speed</p>
<input type="button" value="+" id="btnAdd">
<input type="button" value="-" id="btnSub">
<script>
var x = 0;
var y = 15;
var speed = 10;
var isRight = true;
document.getElementById('text').innerText = speed;
document.getElementById('btnAdd').addEventListener('click', function (event) {
if (isRight) speed++;
else speed--;
document.getElementById('text').innerText = speed;
});
document.getElementById('btnSub').addEventListener('click', function (event) {
if (isRight) speed--;
else speed++;
document.getElementById('text').innerText = speed;
});
function animate() {
reqAnimFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame;
reqAnimFrame(animate);
x += speed;
if (x <= 0 || x >= 475) {
speed = -speed;
isRight = !isRight;
}
document.getElementById('text').innerText = speed;
draw();
}
function draw() {
var canvas = document.getElementById("ex1");
var context = canvas.getContext("2d");
context.clearRect(0, 0, 525, 200);
context.fillStyle = "#ff00ff";
context.fillRect(x, y, 40, 40);
}
animate();
</script>
video canvas:
<canvas id='canvas'></canvas>
<script type="text/javascript">
var video = document.createElement('video');
video.src = 'gold.mp4';
video.controls = true;
document.body.appendChild(video);
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d');
video.onplay = function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
draw();
};
function draw() {
if(video.paused || video.ended) return false;
ctx.drawImage(video, 0, 0);
setTimeout(draw, 20);
}
</script>
Upvotes: 2
Views: 387
Reputation: 4400
First you want to set the position property of the canvas elements to absolute
. Then for each canvas, you want to set their z-index
.
For example, if you want element with class canvasOne
to be behind canvasTwo
canvas {
position: absolute;
}
.canvasOne {
z-index: -1;
}
.canvasTwo {
z-index: 0;
}
What the absolute positioning achieves is that it allows you to set multiple elements to the same position because it takes the elements out of the normal flow of the page.
z-index allows you to control the stack ordering of the elements, or, in other words, the order of the element layers.
Upvotes: 2
Reputation: 558
everything you need is to set a different z-index css property of canvases http://www.w3schools.com/cssref/pr_pos_z-index.asp
Upvotes: 0