canvas水位进度效果代码实例

2018-2-11 08:04| 作者: antzone| 查看: 1397| 评论: 0|来自: 蚂蚁部落

分享一段代码实例,它实现利用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>
1

鲜花

握手

雷人

路过

鸡蛋

刚表态过的朋友 (1 人)

最新评论

返回顶部