我所拥有的是一个覆盖画布元素,其中的浮动粒子在屏幕周围反弹,旨在模拟浮动的叶子和/或灰尘粒子。画布元素覆盖了风景优美的背景,当在移动设备上查看页面时,粒子似乎太大而无法看成漂浮的叶子/灰尘,它们看起来像是漂浮的球,阻碍了人们想象它们是叶子/灰尘。
我想在浏览器屏幕小于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);
最佳答案
调整窗口调整大小事件的半径。
function setRadius(value) {
self.radius = value;
}
function resize(event) {
if ($(window).width() > 600) {
setRadius(.9 * Math.random() + 10);
} else {
setRadius(.9 * Math.random() + 2);
}
}
resize();
$(window).on('resize', resize);
工作演示:http://jsfiddle.net/x5rwgcfv/3/
关于javascript - HTML5 Canvas float 颗粒自适应修复程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30019194/