我使用HTML5画布有两个不同的代码。我希望能够将两者结合在一起。我希望视频出现在动画广场的背景中。有没有办法在HTML5 Canvas中做到这一点?
方形动画:
<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>
视频画布:
<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>
答案 0 :(得分:2)
首先,您要将canvas元素的position属性设置为absolute
。然后,对于每个画布,您要设置其z-index
。
例如,如果您希望类canvasOne
的元素位于canvasTwo
canvas {
position: absolute;
}
.canvasOne {
z-index: -1;
}
.canvasTwo {
z-index: 0;
}
绝对positioning实现的是它允许您将多个元素设置为相同的位置,因为它将元素从页面的正常流中取出。
z-index允许您控制元素的堆栈顺序,换句话说,控制元素图层的顺序。
答案 1 :(得分:0)
您需要的一切是设置画布的不同z-index css属性 http://www.w3schools.com/cssref/pr_pos_z-index.asp