在这个论坛的帮助下,我写了一些代码来制作一个放入篮子的球的动画。
我的想法是用户必须在一个时间限制内写下数学运算的结果。如果他做对了,球会进入篮筐。
唯一的问题是我无法找到如何延迟动画的开始。我的目标是拥有一个带球和篮子的固定帆布,然后在时间限制结束时我希望球开始移动。我试图使用我从互联网上获得的sleep()
功能,但很快我就知道它给了我比其他任何东西更多的麻烦。这是我的代码的一部分:
const tabx = 800, taby = 100; //backboard position
var canvas, ctx, i=0;
function init(z) { //z is the state of the function, at the start is 0 then goes to 1
canvas = document.getElementById("mycanvas");
ctx = canvas.getContext("2d");
//backboard
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.rect(tabx, taby, 180, 100);
ctx.stroke();
//basket
ctx.scale(1, 0.5);
ctx.beginPath();
ctx.arc(890, 320, 35, 0, 2 * Math.PI, false);
ctx.stroke();
ctx.moveTo(855, 320);
ctx.lineTo(865, 445);
ctx.stroke();
ctx.moveTo(925, 320);
ctx.lineTo(915, 445);
ctx.stroke();
ctx.scale(1, 0.15);
ctx.beginPath();
ctx.arc(890, 2980, 25, 0, 2 * Math.PI, false);
ctx.stroke();
ctx.setTransform(1, 0, 0, 1, 0, 0); //setting transformation to default
if (z == 0){
start();
}
}
function start() {
var x1, y1, a, b, c, denom,x3,y3;
//generating ball position
x1 = (Math.random() * 500) + 100;
y1 = (Math.random() * 200) + 300;
canvas = document.getElementById("mycanvas");
ctx = canvas.getContext("2d");
//setting the end point of the parabola
x3 = tabx + 90;
y3 = taby + 90;
//setting the medium point of the parabola
x2 = (x1 + (x3+90))/ 2;
y2 = ((y1 + (y3+220)) / 2) - 300;
//calculating the equation of the parabola
denom = (x1 - x2) * (x1 - x3) * (x2 - x3);
a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom;
b = (x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1) + x1 * x1 * (y2 - y3)) / denom;
c = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom;
drawball(a, b, c, x1, y1,x3);
}
function drawball(a, b, c, x1, y1, x3){
var ris;
canvas = document.getElementById("mycanvas");
ctx = canvas.getContext("2d");
//ball drawing
ctx.beginPath();
ctx.arc(x1, y1, 25, 0, 2 * Math.PI);
ctx.stroke();
if(i==1){
sleep(3000);
ris=genmat();
}
i++;
if (x1 < x3) {
window.requestAnimationFrame(function() {
ctx.clearRect(0, 0, 1000, 600);
init(1); //calling the init function to redraw everything
y1 = a * (x1 * x1) + b * x1 + c;
x1 += 10;
//drawing the next ball
drawpalla(a, b, c, x1, y1,x3)
});
}
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
//function that generates the operation
function genmat(){
var n1,n2,op,ris;
n1=Math.trunc(Math.random()*10)
n2=Math.trunc(Math.random()*10)
op=Math.trunc((Math.random()*(4-1))+1)
if(op==1){
op="+";
ris=n1+n2;
}
if(op==2){
op="-";
ris=n1-n2;
}
if(op==3){
op="*";
ris=n1*n2;
}
if(op==4){
op="/";
ris=n1/n2;
}
document.getElementById("mate").innerHTML=n1+op+n2;
return ris;
}
感谢您的帮助。