canvas圓形隨機漂浮效果

admin發表於2017-02-17

分享一段程式碼例項,它利用canvas實現了圓形隨機漂浮效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="canvas" width="500" height="500">瀏覽器不支援</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//瀏覽器寬高
var screenWidth = document.documentElement.clientWidth;
var screenHeight = document.documentElement.clientHeight;
 
canvas.width = screenWidth; //顯示螢幕的畫素
canvas.height = screenHeight; //顯示螢幕的高度
 
//隨機函式
function rand(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}
 
function Ball() {
  //半徑
  this.r = rand(5, 100);
  //圓心
  this.x = rand(this.r, screenWidth - this.r);
  this.y = rand(this.r, screenHeight - this.r);
  //顏色
  this.color = "rgba(" + rand(0, 255) + "," + rand(0, 255) + "," + rand(0, 255) + "," + Math.random() + ")";
  //速度
  this.speedX = rand(1, 3) * (rand(0, 3) > 1 ? 1 : -1);
  this.speedY = rand(1, 4) * (rand(0, 3) > 1 ? 1 : -1);
}
 
//位置變化
Ball.prototype.move = function() {
  this.x += this.speedX;
  this.y += this.speedY;
  if (this.x >= screenWidth - this.r) {
    this.speedX *= -1;
  }
  if (this.x <= this.r) {
    this.speedX *= -1;
  }
  if (this.y >= screenHeight - this.r) {
    this.speedY *= -1;
  }
  if (this.y <= this.r) {
    this.speedY *= -1;
  }
}
 
 
//畫出圓形
Ball.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fill();
}
 
var balls = [];
for (var i = 0; i < 20; i++) {
  var ball = new Ball();
  balls.push(ball);
  ball.draw();
}
 
//迴圈移動
function move() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < balls.length; i++) {
    var ball = balls[i]
    ball.draw();
    ball.move();
  }
  window.requestAnimationFrame(move);
}
move()
</script>
</body>
</html>

相關文章