利用JS+Canvas給南方的冬季來一場紛紛揚揚的大雪
前言
今年冬季都快接近尾聲了,身處在南方的我,一點小雪花都還沒見到。今年感覺也沒以往的冬季冷,以往的冬季就不太能見到一場大雪,今年估計更不可能見到一場大雪紛飛的景色了,因此,用代碼來實現一場紛紛揚揚的大雪,完成自己今年看雪的愿望。
具體實現
使用Canvas實現雪花紛飛的場景。
1. 頁面布局
頁面html,body 設置寬100%、高100vh,鋪滿整個屏幕,并設置一張好看的背景圖或者背景色,能夠很好地和白色的雪花相融合
2. 雪花的實現
定義一個類:雪花Snowflake,首先設計每一片雪花對象的數據結構:
a. 雪花的坐標x、y坐標,以及左右移動的速度vx、vy。(由于雪花的位置是不斷移動的)
x坐標 0到窗口寬度的一個隨機數
y坐標 0到窗口高度的一個隨機數(因為雪花是從頁面上方進入頁面,因此窗口高度要為負值)
左右移動的速度vx、vy 任意取兩個合適的數值的隨機數
b. 雪花的半徑radius
c. 雪花的透明度alpha
每一片雪花的坐標、移動速度、半徑、透明度都是隨機生成的
更新雪花的位置:當雪花移動到頁面最底部,需要更新每一片雪花的數據
class Snowflake {
constructor() {
this.x = 0;
this.y = 0;
this.vx = 0;
this.vy = 0;
this.radius = 0;
this.alpha = 0;
this.reset();
}
reset() {
this.x = this.randBetween(0, window.innerWidth);
this.y = this.randBetween(0, -window.innerHeight);
this.vx = this.randBetween(-3, 3);
this.vy = this.randBetween(2, 5);
this.radius = this.randBetween(1, 4);
this.alpha = this.randBetween(0.1, 0.9);
}
randBetween(min, max) {
return min + Math.random() * (max - min);
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.y + this.radius > window.innerHeight) {
this.reset();
}
}
}3. 實現下雪
a. 使用js創(chuàng)建元素Canvas,定義一個畫布,并添加到body元素中
b. 設置畫布的大小,并且監(jiān)聽窗口,當窗口大小發(fā)生改變時,也需要調整畫布的大?。ê痛翱诘膶捀咭粯樱?,以便保證Canvas是滿屏的
c. 實現下雪的效果
生成雪花,生成雪花的數量根據窗口寬度的4分之一設置。并設置一個數組保存生成的每片雪花對象,以便requestAnimationFrame函數在調用時候,更改各個雪花的位置,從而實現下雪的效果
使用Canvas畫雪
class Snow {
constructor() {
this.canvas = document.createElement("canvas");
this.ctx = this.canvas.getContext("2d");
document.body.appendChild(this.canvas);
window.addEventListener("resize", () => this.onResize());
this.onResize();
this.updateBound = this.update.bind(this);
//實現動畫
requestAnimationFrame(this.updateBound);
this.createSnowflakes();
}
onResize() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.canvas.width = this.width;
this.canvas.height = this.height;
}
createSnowflakes() {
const flakes = window.innerWidth / 4;
this.snowflakes = [];
for (let s = 0; s < flakes; s++) {
this.snowflakes.push(new Snowflake());
}
}
update() {
//清除原來上面的雪花
this.ctx.clearRect(0, 0, this.width, this.height);
for (let flake of this.snowflakes) {
//計算每一片雪花的新坐標
flake.update();
//在canvas上畫出雪花
this.ctx.save();
this.ctx.fillStyle = "#FFF";
this.ctx.beginPath();
this.ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI * 2);
this.ctx.closePath();
this.ctx.globalAlpha = flake.alpha;
this.ctx.fill();
this.ctx.restore();
}
requestAnimationFrame(this.updateBound);
}
}
new Snow();效果圖展示(ps: 使用css畫了兩個燈籠,下一篇文章講解下怎么實現的)
總結
到此這篇關于利用JS+Canvas給南方的冬季來一場紛紛揚揚的大雪的文章就介紹到這了,更多相關JS+Canvas實現大雪內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!


