有没有人能在HTML5画布中向我展示带有简单动画的播放按钮的概念?
如果到达限制区域,它会自动返回,但我如何通过按钮控制它? 非常感谢。
对于前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();
&#13;
<canvas id="assignmenttwoCanvas" width="500" height="500"></canvas>
&#13;
答案 0 :(得分:0)
这是如何做到的。
<强> 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();
&#13;
<canvas id="assignmenttwoCanvas" width="500" height="500"></canvas>
<button id="reverse" onclick=reverse()>Reverse</button>
&#13;