作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有人可以向我展示 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/
我是一名优秀的程序员,十分优秀!