gpt4 book ai didi

javascript - 如何用html5制作播放按钮?

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

有人可以向我展示 HTML5 Canvas 中带有简单动画的播放按钮的概念吗?

到达限制区域后会自动返回,但如何通过按钮控制它?太感谢了。

对于前1

var context;

function setupAnimCanvas() {
var canvas = document.getElementById('assignmenttwoCanvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
//setInterval('draw();', 20); //don't use this
img = new Image();
img.onload = function(e) {
draw(); //use this instead..
}
img.src = '../images/dragon.png';
//animation();
draw(); //as we don't have an image to load, call here
//remove when image is used instead
}
}
var startPos = [500, 500];
var endPos = [0, 0];
var dx = -3, dy = -3;
var x = startPos[0], y = startPos[1];

function draw() {
ctx.clearRect(0, 0, 500, 500);
//drawBackground();
//ctx.drawImage(img, x, y);
ctx.fillRect(x, y, 20, 20); //for demo as no image
x += dx;
y += dy;

if (x < endPos[0] || x > startPos[0] ||
y < endPos[1] || y > startPos[1] ) {
dx = -dx;
dy = -dy;
}
//moveit();
setTimeout(draw, 16);
}
setupAnimCanvas();
<canvas id="assignmenttwoCanvas" width="500" height="500"></canvas>

最佳答案

具体操作方法如下。

<强> SEE FIDDLE

点击按钮会触发反向

var context;
var startPos = [500, 500];
var endPos = [0, 0];
var dx = -3, dy = -3;
var x = startPos[0], y = startPos[1];

function reverse(){

dx = -dx;
dy = -dy;
}

function setupAnimCanvas() {
var canvas = document.getElementById('assignmenttwoCanvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
//setInterval('draw();', 20); //don't use this
img = new Image();
img.onload = function(e) {
draw(); //use this instead..
}
img.src = '../images/dragon.png';
//animation();
draw(); //as we don't have an image to load, call here
//remove when image is used instead
}
}



function draw() {
ctx.clearRect(0, 0, 500, 500);
//drawBackground();
//ctx.drawImage(img, x, y);
ctx.fillRect(x, y, 20, 20); //for demo as no image
x += dx;
y += dy;

if (x < endPos[0] || x > startPos[0] ||
y < endPos[1] || y > startPos[1] ) {
dx = -dx;
dy = -dy;
}
//moveit();
setTimeout(draw, 16);
}
setupAnimCanvas();
<canvas id="assignmenttwoCanvas" width="500" height="500"></canvas>
<button id="reverse" onclick=reverse()>Reverse</button>

关于javascript - 如何用html5制作播放按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271835/

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