【发布时间】:2018-01-03 11:56:22
【问题描述】:
我正在尝试循环播放我的动画,但无论我做什么,它都不会循环播放。总的来说,我对 canvas、javascript 和代码还是很陌生。
var canvas = document.getElementById("fabrication");
var ctx = canvas.getContext("2d");
var background = new Image();
background.src =
"C:/Users/dylan/Desktop/ProjectTwo/Images/fabricationbackground.jpg";
background.onload = function(){
}
//Loading all of my canvas
var posi =[];
posi[1] = 20;
posi[2] = 20;
var dx=10;
var dy=10;
var ballRadius = 4;
//Variables for drawing a ball and it's movement
function drawballleft(){
posi =xy(posi[1],posi[2])
}
function xy(x,y){
ctx.drawImage(background,0,0);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#FFFFFFF";
ctx.fill();
ctx.closePath();
var newpos=[];
newpos[1]= x +dx;
newpos[2]= y +dy;
return newpos;
//Drawing the ball, making it move off canvas.
if (newpos[1] > canvas.width) {
newpos[1] = 20;
}
if (newpos[2] > canvas.height) {
newpos[2] = 20;
}
//If statement to detect if the ball moves off the canvas, to make it return to original spot
}
setInterval(drawballleft, 20);
//Looping the function
如果我做错了什么,请告诉我,我真的很想知道我在这里做什么。球应该离开画布,然后循环回到自己身上,但它离开了画布并结束了。
提前致谢!
【问题讨论】:
-
尝试使用 .push() 设置 newpos 值,就像 newpos.push(20) 一样,并记住数组索引从 0 而不是 1 开始。
-
不要使用
file://。使用真实的静态服务器。大多数 IDE 都内置了此功能。您也可以使用http-server模块。
标签: javascript html animation canvas