【发布时间】:2018-09-25 15:53:54
【问题描述】:
我所拥有的是一个覆盖画布元素,带有在屏幕上反弹的浮动粒子,旨在模仿漂浮的叶子和/或灰尘粒子。画布元素覆盖了风景背景,当在移动设备上查看页面时,粒子似乎太大而无法被视为漂浮的树叶/灰尘,它们看起来像漂浮在周围的球,这阻碍了它们是树叶/灰尘的想象。
我想在浏览器屏幕小于 600px 时调整粒子的大小,但我不知道如何修改代码。
这里是使用的JS:
(function() {
jQuery(function() {
var H, Particle, W, animateParticles, canvas, clearCanvas, colorArray, createParticles, ctx, drawParticles, initParticleSystem, particleCount, particles, updateParticles;
Particle = function() {
this.color = colorArray[Math.floor((Math.random() * 5) + 1)];
this.x = Math.random() * W;
this.y = Math.random() * H;
this.direction = {
x: -1 + Math.random() * 2,
y: -1 + Math.random() * 1
};
this.vx = 1 * Math.random() + .05;
this.vy = 1 * Math.random() + .05;
this.radius = .9 * Math.random() + 1;
this.move = function() {
this.x += this.vx * this.direction.x;
this.y += this.vy * this.direction.y;
};
this.changeDirection = function(axis) {
this.direction[axis] *= -1;
};
this.draw = function() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fill();
};
this.boundaryCheck = function() {
if (this.x >= W) {
this.x = W;
this.changeDirection("x");
} else if (this.x <= 0) {
this.x = 0;
this.changeDirection("x");
}
if (this.y >= H) {
this.y = H;
this.changeDirection("y");
} else if (this.y <= 0) {
this.y = 0;
this.changeDirection("y");
}
};
};
clearCanvas = function() {
ctx.clearRect(0, 0, W, H);
};
createParticles = function() {
var i, p;
i = particleCount - 1;
while (i >= 0) {
p = new Particle();
particles.push(p);
i--;
}
};
drawParticles = function() {
var i, p;
i = particleCount - 1;
while (i >= 0) {
p = particles[i];
p.draw();
i--;
}
};
updateParticles = function() {
var i, p;
i = particles.length - 1;
while (i >= 0) {
p = particles[i];
p.move();
p.boundaryCheck();
i--;
}
};
initParticleSystem = function() {
createParticles();
drawParticles();
};
animateParticles = function() {
clearCanvas();
drawParticles();
updateParticles();
requestAnimationFrame(animateParticles);
};
W = void 0;
H = void 0;
canvas = void 0;
ctx = void 0;
particleCount = 100;
particles = [];
colorArray = ["rgba(65,61,11,.5)", "rgba(112,94,12,.6)", "rgba(129,123,114,.4)", "rgba(122,105,17,.5)", "rgba(188,188,188,.2)", "rgba(75,69,16,.5)", "rgba(136,107,13,.5)"];
W = window.innerWidth;
H = jQuery('.fullscreen-cover').height();
canvas = jQuery("#headerballs").get(0);
canvas.width = W;
canvas.height = H;
ctx = canvas.getContext("2d");
initParticleSystem();
requestAnimationFrame(animateParticles);
});
}).call(this);
【问题讨论】:
标签: javascript html canvas