JS結合Canvas畫運動小球
作者:王珮云
canvas是HTML5新增的元素,也被稱為畫布,可以結合javascript實現繪制各種圖形,制作各種炫酷的動畫效果,現在我們也來使用canvas畫隨機運動小球。
前言
canvas是HTML5新增的元素,也被稱為畫布,可以結合javascript實現繪制各種圖形,制作各種炫酷的動畫效果,現在我們也來使用canvas畫隨機運動小球。
實現思路
- 首先為了達到我們想要的效果,可以先創建一個構造函數。
- 給構造函數添加對應的屬性和方法。
- 實例化出多個對象,并且保存在數組中。
- 遍歷每個對象,實現畫圓。
- 間隔修改每個球的x,y值。
先準備畫布確定對應的寬高:
<canvas id="canvas" width="400" height="400"></canvas>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let maxWidth = canvas.width,
maxHeight = canvas.height;
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, maxWidth, maxHeight);
</script>
因為是隨機運動,所以要創建一個獲取隨機數的方法:
function getRandomNum(minNum, maxNum) {
switch (arguments.length) {
case 1:
return Math.round(Math.random() * minNum + minNum);
break;
case 2:
return Math.round(
Math.random() * (maxNum - minNum) + minNum);
break;
case 0:
return 0;
break;
}
}
// 創建一個Ball的構造函數
function Ball(maxWidth, maxHeight, ctx) {
this.ctx = ctx;
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
// 隨機半徑
this.r = getRandomNum(5, 15);
// 隨機x,y坐標
this.x = getRandomNum(this.r, this.maxWidth - this.r);
this.y = getRandomNum(this.r, this.maxHeight - this.r);
// 平移速度,正負區間是為了移動方向多樣
this.speedX = getRandomNum(-2, 2);
this.speedY = getRandomNum(-2, 2);
// 顏色隨機
this.color = `rgba(${getRandomNum(0, 255)},
${getRandomNum(0, 255)},
${getRandomNum(0, 255)},${Math.random()})`;
}
Ball.prototype = {
draw: function () {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
},
move: function () {
// 判斷邊界值,讓圓球始終保證在畫面內
if (this.x > this.maxWidth - this.r || this.x < this.r) {
this.speedX = -this.speedX;
}
if (this.y > this.maxHeight - this.r || this.y < this.r) {
this.speedY = -this.speedY;
}
this.x += this.speedX;
this.y += this.speedY;
}
};
// 創建100個Ball實例
let balls = [];
for (let i = 0; i < 100; i++) {
let newBall = new Ball(maxWidth, maxHeight, ctx);
newBall.draw();
balls.push(newBall);
}
靜態效果
現在我們畫出了不同半徑和顏色的靜止圓球。
調用move方法,間隔修改每個球的x,y值。
setInterval(() => {
// 每次畫之前都要清除畫布
ctx.clearRect(0, 0, maxWidth, maxHeight);
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, maxWidth, maxHeight);
for (let j = 0; j < 100; j++) {
balls[j].draw(ctx);
balls[j].move();
}
}, 100);
效果展示。
總結
canvas強大的繪圖能力可以使網頁的內容更加豐富多彩,給用戶帶來更好的視覺效果和和交互體驗,掌握一些功能的使用可以讓我們的項目更好的理解與canvas相關的框架使用,也能夠創建豐富的web應用,同時也要求我們更好的掌握javascript。
責任編輯:jianghua
來源:
鴻蒙社區