我目前正试图在画布中产生闪光的效果。然而,当我测试动画时,我注意到一些圆圈会被删除,然后再次出现。
这似乎是由剪接消除了一个更高指数的火花所造成的。当火花缩小到半径为0时,你就会注意到闪光灯。如果这就是造成这个问题的真正原因,我真的不明白为什么拼接会引起这样的问题。
https://jsfiddle.net/sketti21/2gfarp74/82/
// Handles the animation of the sparkles.
function animate(timestamp)
{
// Observe the timestamp gives by requestAnimationFrame in console.
// console.log(timestamp);
// Clears the previous frame;
draw.clearRect(0, 0, canvas.width, canvas.height);
// Loop through each index of sparkles. Doing this lets us draw multiple
// sparkles at once.
for (i = 0; i < sparkles.length; i++)
{
if (sparkles[i] != null)
{
// If the sparkle's delay is not set, then set it.
// This is necessary to do here since the timestamp that requestAnimationFrame
// puts in as a parameter is always growing.
if (sparkles[i].delay == null)
{
sparkles[i].delay = Math.floor(Math.random()*config.maxDelay) + timestamp;
}
// Handles whether to animate the next frame or to remove this sparkle from array.
// If timestamp is larger than sparkle's delay, this means it's time to
// animate this sparkle.
if (timestamp > sparkles[i].delay)
{
// Increment the input variable and calculate the radius of circle.
sparkles[i].inputX += config.increment;
var radius = getRadius(sparkles[i].inputX, sparkles[i].multiplier);
console.log("Radius of index " + i + ": " + radius);
console.log("Multiplier of index " + i + ": " + sparkles[i].multiplier);
if (radius < 0)
{
radius = 0;
}
// Drawing the circle.
draw.beginPath();
draw.arc(sparkles[i].x,
sparkles[i].y,
radius, 0, 360);
draw.fill();
draw.closePath();
// If the sparkle's radius drops below 0, then remove it from the array.
if (radius == 0)
{
sparkles.splice(i, 1);
console.log("spliced indexes " + i + " to " + (i + 1));
}
}
}
}
if (sparkles.length > 0)
{
animControl = window.requestAnimationFrame(animate);
}
else
{
console.log("Refilled the array.");
for (i = 0; i < config.maxSparkles; i++)
{
sparkles[i] = new Sparkle();
}
animControl = window.requestAnimationFrame(animate);
}
}让我总结一下代码的逻辑,以便更快、更容易地阅读代码:
8a.计算并绘制该框架的每个火花。
8b.如果星光半径= 0,则将火花阵列中的火花拼接出来。如果火花阵列中有元素,则
9a.否则,将数组填充到config.maxSparkles.
..。就这样等等。
任何帮助都是非常感谢的!
发布于 2019-10-19 21:19:18
当您从数组中拼接某物时,一个元素会被移除,因此长度会缩短一个。
因此,如果循环遍历数组并删除某些内容,这意味着要删除的项的索引现在已成为下一个项的索引。因此,在下一个循环中,该项被跳过。
为了解决您的问题,当您从数组中拼接一些东西时,需要减少i,这样就不会在下一次迭代中跳过它。
希望这能解决问题!
https://stackoverflow.com/questions/58467599
复制相似问题