由於使用的是vue開發,所以就展示一下繪製函數好了,上圖是效果圖 drawMain(drawing_elem, percent, forecolor, bgcolor) { /* @drawing_elem: 繪製對象 @percent:繪製圓環百分比, 範圍[0, 100] @forecolor: ...
由於使用的是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博主「前端小白的江湖路」的原創文章https://blog.csdn.net/qq_21058391/article/details/76691047