gpt4 book ai didi

javascript - HTML5 Canvas 分层

转载 作者:行者123 更新时间:2023-11-28 00:02:43 25 4
gpt4 key购买 nike

我有 2 个使用 HTML5 Canvas 的不同代码。我希望能够将两者叠加在一起。我希望视频出现在动画方 block 的背景中。有没有办法在 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 :

 <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>

最佳答案

首先,您要将 Canvas 元素的位置属性设置为absolute。然后对于每个 Canvas ,您要设置它们的 z-index

例如,如果您希望类为 canvasOne 的元素位于 canvasTwo 之后

canvas { 
position: absolute;
}

.canvasOne {
z-index: -1;
}

.canvasTwo {
z-index: 0;
}

什么绝对positioning实现的是它允许您将多个元素设置到同一位置,因为它使元素脱离了页面的正常流动。

z-index允许您控制元素的堆叠顺序,或者换句话说,控制元素层的顺序。

关于javascript - HTML5 Canvas 分层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com