canvas水位进度效果代码实例
分类:实例代码
canvas水位进度效果代码实例属于前端实例代码,有关更多实例代码大家可以查看。
分享一段代码实例,它实现利用canvas绘制水位效果的进度功能。
根据水位的动态上升和下降来标识进度,图示如下:
代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <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>
canvas水位进度效果代码实例,这样的场景在实际项目中还是用的比较多的,关于canvas水位进度效果代码实例就介绍到这了。