canvas水位進度效果程式碼例項

antzone發表於2018-02-11

分享一段程式碼例項,它實現利用canvas繪製水位效果的進度功能。

根據水位的動態上升和下降來標識進度,圖示如下:

a:3:{s:3:\"pic\";s:43:\"portal/201802/11/144312aeeznuc3e738j3gj.png\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="can1" width="300" height="250"></canvas>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
let page = {
  ctx: $('#can1')[0].getContext('2d'),
 
  cx: 100,
  cy: 100,
 
  lx: 100,
  lx2: 100,
  ly: 80, //範圍80~160
  ly2: 100,
 
  r: 80,
 
  init: function() {
    let self = this,
      status = "minus",
      status2 = "minus";
 
    let timer = setInterval(function() {
      //清空canvas
      self.ctx.clearRect(0, 0, 300, 250);
 
      //計算Y對應的X
      let expression = Math.pow(self.r, 2) - Math.pow((self.cy - self.ly), 2);
      let expression2 = Math.pow(self.r, 2) - Math.pow((self.cy - self.ly2), 2);
      self.lx = Math.sqrt(expression);
      self.lx2 = Math.sqrt(expression2);
 
      //畫圓
      self.ctx.strokeStyle = "orange";
      self.ctx.beginPath();
      self.ctx.arc(self.cx, self.cy, self.r, 0, Math.PI * 2, false);
      self.ctx.stroke();
 
      //計算圓弧
      let angle = Math.asin(Math.abs(self.cy - self.ly) / self.r);
      let angleRight = Math.asin(Math.abs(self.cy - self.ly2) / self.r);
      if (self.ly < self.cy) {
        angle += Math.PI;
      } else {
        angle = Math.PI - angle;
      }
 
      if (self.ly2 < self.cy) {
        angleRight = 2 * Math.PI - angleRight;
      }
 
 
      //畫直線
      self.ctx.beginPath();
      self.ctx.fillStyle = "rgba(0,177,255, 0.3)";
      self.ctx.moveTo(self.cx - self.lx, self.ly);
      self.ctx.bezierCurveTo(self.cy, self.ly, self.cy, self.ly2 - 40, self.cx + self.lx2, self.ly2);
 
      self.ctx.arc(self.cx, self.cy, self.r, angleRight, angle, false);
      self.ctx.fill();
 
      self.ctx.beginPath();
      self.ctx.fillStyle = "rgba(0,100,255, 0.4)";
      self.ctx.moveTo(self.cx - self.lx, self.ly);
      self.ctx.bezierCurveTo(self.cy, self.ly - 50, self.cy, self.ly2 + 10, self.cx + self.lx2, self.ly2);
 
      self.ctx.arc(self.cx, self.cy, self.r, angleRight, angle, false);
      self.ctx.fill();
 
      if (status == "minus") {
        if (self.ly < 80) {
          status = "add";
        }
        self.ly--;
      } else {
        self.ly++;
        if (self.ly > 120) {
          status = "minus";
        }
      }
 
      if (status2 == "minus") {
        if (self.ly2 < 80) {
          status2 = "add";
        }
        self.ly2--;
      } else {
        self.ly2++;
        if (self.ly2 > 120) {
          status2 = "minus";
        }
      }
 
    }, 40)
  },
}
page.init();
</script>
</body>
</html>

相關文章