canvas 绘制动态圆环进度条
由于使用的是vue开发,所以就展示一下绘制函数好了,上图是效果图
drawmain(drawing_elem, percent, forecolor, bgcolor) {
/*
@drawing_elem: 绘制对象
@percent:绘制圆环百分比, 范围[0, 100]
@forecolor: 绘制圆环的前景色,颜色代码
@bgcolor: 绘制圆环的背景色,颜色代码
*/
var context = drawing_elem.getcontext("2d");
var center_x = drawing_elem.width / 2;
var center_y = drawing_elem.height / 2;
var rad = math.pi*2/100;
var speed = 0;
// 绘制背景圆圈
function backgroundcircle(){
context.save();
context.beginpath();
context.linewidth = 8; //设置线宽
var radius = center_x - context.linewidth;
context.linecap = "round";
context.strokestyle = bgcolor;
context.arc(center_x, center_y, radius, 0, math.pi*2, false);
context.stroke();
context.closepath();
context.restore();
}
//绘制运动圆环
function foregroundcircle(n){
context.save();
context.strokestyle = forecolor;
context.linewidth = 8;
context.linecap = "round";
var radius = center_x - context.linewidth;
context.beginpath();
context.arc(center_x, center_y, radius , -math.pi/2, -math.pi/2 +n*rad, false); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
context.stroke();
context.closepath();
context.restore();
}
//绘制文字
function text(n){
context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
context.fillstyle = forecolor;
var font_size = 40;
context.font = font_size + "px helvetica";
var text_width = context.measuretext(n.tofixed(0)+"%").width;
context.filltext(n.tofixed(0)+"%", center_x-text_width/2, center_y + font_size/2);
context.restore();
}
//执行动画
(function drawframe(){
window.requestanimationframe(drawframe);
context.clearrect(0, 0, drawing_elem.width, drawing_elem.height);
backgroundcircle();
text(speed);
foregroundcircle(speed);
if(speed >= percent) return;
speed += 1;
}());
},
调用的话
var time_canvas = document.getelementbyid("time-graph-canvas");
this.drawmain(time_canvas, 70, "#85d824", "#eef7e4");
var weather_canvas = document.getelementbyid("weather-graph-canvas");
this.drawmain(weather_canvas, 90, "#2ba0fb", "#e5f1fa");
html文件
<div class="time-graph">
<canvas id="time-graph-canvas" width="160" height="160"></canvas>
</div>
css文件
.time-graph {
padding-top: 20px;
display:flex;
display:-webkit-flex;
justify-content: center;
align-items: center;
}
#time-graph-canvas {
width: 80px;
height: 80px;
}
有些绘制细节需要注意,为了保证绘制的清晰度,canvas的大小需要设置为canvas父元素大小的2倍。
其他的代码都有详细的注释,自己拷一下,运行一下就知道
————————————————
转自:本文为csdn博主「前端小白的江湖路」的原创文章
下一篇: 用PS制作漂亮的卡通彩色铅笔图标