canvas實現簡答動畫張閉嘴效果

admin發表於2017-02-20
分享一段程式碼例項,它實現了簡單的動畫效果。

嘴巴能夠不斷的張閉,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
canvas {
  border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
 
function Pacman() {
  this.isOpen = true;
  this.start = 45 * Math.PI / 180;
  this.end = 315 * Math.PI / 180;
  this.paint = function() {
      context.beginPath();
      context.arc(250, 200, 100, this.start, this.end);
      context.lineTo(250, 200);
      context.closePath();
      context.fillStyle = "yellow";
      context.fill();
      context.stroke();
 
      context.beginPath();
      context.arc(250, 150, 15, 0, Math.PI * 2);
      context.fillStyle = "black";
      context.fill();
 
      context.beginPath();
      context.arc(255, 145, 5, 0, Math.PI * 2);
      context.fillStyle = "white";
      context.fill();
    }
  this.open = function() {
    if (this.isOpen) { 
      this.start = 45 * Math.PI / 180;
      this.end = 315 * Math.PI / 180;
      this.isOpen = false;
    } else { 
      this.start = 0;
      this.end = Math.PI * 2;
      this.isOpen = true;
    }
  }
}
var pacman = new Pacman();
 
setInterval(function() {
  context.clearRect(0, 0, canvas.width, canvas.height);
 
  pacman.paint();
  pacman.open();
}, 200);
</script>
</body>
</html>

相關文章