【发布时间】:2018-01-26 20:25:23
【问题描述】:
代码(纯js)用于创建动画彩虹,其中连续的彩虹会延迟一点时间。但是动画并不一致(最终会变慢)。我只是编程的初学者,所以我的代码也越来越长。
如果您在本地运行代码,动画会在一段时间后变慢,并且彩虹出现的方式不一致(每条彩虹之间应该有时间间隔)。我的第二个问题是我想减少代码,这样我就不必为每个彩虹动画创建一个函数。
function anim()
{
var x,y,z,p,q,r;
x = y = z = p = q = r = 2*Math.PI;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0,0,c.width,c.height);
var id = setInterval(frame_one,1);
var t = setInterval(frame_two,1);
var u = setInterval(frame_three,1);
var v = setInterval(frame_four,1);
var w = setInterval(frame_five,1);
var s = setInterval(frame_six,1);
function frame_one()
{
if (x <=(Math.PI))
{
clearInterval(id);
x = 2*Math.PI;
}
else
{
x = x - 0.036;
ctx.lineWidth = 20;
ctx.beginPath();
ctx.arc(c.width/2, c.height/2, c.height/2-20, 2* Math.PI,x,true);
ctx.strokeStyle="red";
ctx.stroke();
}
}
function frame_two()
{
if (y <= (Math.PI))
{
y = 2*Math.PI;
clearInterval(t);
}
else
{
y= y - 0.032;
ctx.beginPath();
ctx.lineWidth=20;
ctx.arc(c.width/2,c.height/2, c.height/2-40, 2* Math.PI,y,true);
ctx.strokeStyle="orange";
ctx.stroke();
}
}
function frame_three()
{
if (z <= (Math.PI))
{
clearInterval(u);
}
else
{
z = z - 0.028;
ctx.beginPath();
ctx.lineWidth = 20;
ctx.arc(c.width/2,c.height/2,(c.height)/2-60, 2* Math.PI,z,true);
ctx.strokeStyle = "yellow";
ctx.stroke();
}
}
function frame_four()
{
if (p <= (Math.PI))
{
clearInterval(v);
}
else
{
p = p - 0.024;
ctx.beginPath();
ctx.lineWidth = 20;
ctx.arc(c.width/2,c.height/2,(c.height)/2-80, 2* Math.PI,p,true);
ctx.strokeStyle = "green";
ctx.stroke();
}
}
function frame_five()
{
if (q <= (Math.PI))
{
clearInterval(w);
}
else
{
q = q - 0.020;
ctx.beginPath();
ctx.lineWidth = 20;
ctx.arc(c.width/2,c.height/2,(c.height)/2-100, 2* Math.PI,q,true);
ctx.strokeStyle = "blue";
ctx.stroke();
}
}
function frame_six()
{
if (r <= (Math.PI))
{
clearInterval(s);
}
else
{
r = r - 0.016;
ctx.beginPath();
ctx.lineWidth = 20;
ctx.arc(c.width/2,c.height/2,(c.height)/2-120, 2* Math.PI,r,true);
ctx.strokeStyle = "violet";
ctx.stroke();
}
}
}
anim();
setInterval(anim,3000);
<canvas onclick="info()" id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"></canvas>
【问题讨论】:
-
我不太清楚你的问题是什么,你介意详细说明一下吗?
-
如果你在本地运行代码,动画会在一段时间后变慢,并且彩虹出现的方式没有一致性(每个彩虹之间应该有时间间隔)。我的第二个问题是我想减少代码,这样我就不必为每个彩虹动画都写一个函数