canvas氣泡上浮效果程式碼例項

admin發表於2018-03-19
本章節分享一段程式碼例項,它使用canvas實現了氣泡上浮的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>  
window.onload = function () {
  function Circle() {
    this.x = Math.random() * canvas.width;
    this.y = canvas.height;
    this.r = Math.random() * 10;
    //繪製圓形
    this.paint = function () {
      context.beginPath();
      context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
      context.fillStyle = "white";
      context.globalAlpha = 0.5;
      context.fill();
    }
    //控制圓形移動
    this.step = function () {
      this.y--;
    }
  }
  var circles = [];
 
  function createCircles() {
    var circle = new Circle();
    circles[circles.length] = circle;
  }
  function paintCircles() {
    for (var i = 0; i < circles.length; i++) {
      circles[i].paint();
    }
  }
  function stepCircles() {
    for (var i = 0; i < circles.length; i++) {
      circles[i].step();
    }
  }
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  var myimg = new Image();
  myimg.src = "mytest/demo/cite.jpg";
  var timer = "";
  setInterval(function () {
    context.drawImage(myimg, 0, 0);
    timer++;
    if (timer % 20 == 0) {
      createCircles();
    }
    paintCircles();
    stepCircles();
  }, 10);
}
</script>
</head>
<body>
<div id="d1">
  <canvas id="canvas"></canvas>
</div>
</body>
</html>

相關文章