【发布时间】:2019-09-30 08:11:52
【问题描述】:
我正在制作一个五彩纸屑发射器,它可以创建正方形并将它们放置在屏幕顶部,它们每个都有一定的重力和朝向侧面的方向。我有一个按钮,一次可以制作 100 个。然而,每次我按下按钮时,它都会创建新的,但也会加快现有方块的移动。
var width1 = window.innerWidth || document.documentElement.clientWidth ||
document.body.clientWidth;
var height1 = window.innerHeight || document.documentElement.clientHeight ||
document.body.clientHeight;
let canvas = document.getElementById('confetti');
let ctx = canvas.getContext('2d');
canvas.width = width1;
canvas.height = height1;
let pieces = [];
let numberOfPieces = 100;
let lastUpdateTime = Date.now();
var a = 0;
var intervalID;
function randomColor() {
let colors = ['#999999ff', '#b7b7b7ff', ' #D3D3D3', '#ffff00 ', '#d9d9d9ff'];
return colors[Math.floor(Math.random() * colors.length)];
}
function update() {
let now = Date.now(),
dt = now - lastUpdateTime;
for (let i = pieces.length - 1; i >= 0; i--) {
let p = pieces[i];
if (p.y > canvas.height) {
pieces.splice(i, 1);
continue;
}
p.y += p.gravity * dt;
p.rotation += p.rotationSpeed * dt;
p.x += p.direction;
}
if (pieces.length < numberOfPieces) {
for (var b = pieces.length; b < numberOfPieces; b++) {
pieces.push(new Piece(Math.random() * canvas.width, -20));
b--;
numberOfPieces--;
}
}
lastUpdateTime = now;
a++;
if (a >= 1) {
numberOfPieces = 0;
//console.log("number of pieces: " + numberOfPieces + " pieces.length: " + pieces.length);
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
pieces.forEach(function(p) {
ctx.save();
ctx.fillStyle = p.color;
ctx.translate(p.x + p.size / 2, p.y + p.size / 2);
ctx.rotate(p.rotation);
ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size);
ctx.restore();
});
requestAnimationFrame(draw);
}
function Piece(x, y) {
this.x = x;
this.y = y;
this.size = (Math.random() * 0.5 + 0.75) * 15;
this.gravity = (Math.random() * 0.5 + 0.75) * 0.15;
var c = Math.random()
if (c > 0.5) {
this.direction = -(Math.random() * 0.6);
} else {
this.direction = (Math.random() * 0.6);
}
this.rotation = (Math.PI * 2) * Math.random();
this.rotationSpeed = (Math.PI * 2) * (Math.random() - 0.5) * 0.0005;
this.color = randomColor();
}
while (pieces.length < numberOfPieces) {
pieces.push(new Piece(Math.random() * canvas.width, Math.random() * canvas.height));
}
var bye = 0;
function myfunction() {
var hello = Date.now();
var difference = hello - bye;
if (difference > 1000) {
a = 0;
numberOfPieces = pieces.length + 100;
intervalID = setInterval(update, 30);
draw();
bye = Date.now();
}
}
<canvas id="confetti"></canvas>
<button style="float: right; border: 1px blue solid; width: 100px; height: 100px;" onclick="myfunction()">Click me</button>
【问题讨论】:
-
是的,它们是横向的。最初他们几乎喜欢直线下降。 1000 次点击后,横向移动增加。
-
您的每一次按钮点击都会以自己的间隔开始一个新动画,而不是停止前一个动画。单击两次后,您将有两个动画间隔同时运行,它们同时执行两倍的更新次数。
-
另外,为什么你有单独的更新和绘制循环?
标签: javascript html css canvas