react canvas圓環動態百分比

import React from 'react';
import Tools from '../../tools/index'
export default class PercentageRing extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
let canvas = this.refs.ring;
let width = canvas.offsetWidth;
let height = canvas.offsetHeight;
let context = canvas.getContext('2d');
// this.rings();
let i = 1;
let percent = 30;
this.timerId = setInterval(()=>{
i >= percent && clearInterval(this.timerId);
context.clearRect(0,0,width+10,height);
this.draw(i++);
},50)
}

 

draw(i){
let canvas = this.refs.ring;
let width = canvas.offsetWidth;
let height = canvas.offsetHeight;
let context = canvas.getContext('2d');
let rad = Math.PI*2/100;
canvas.width = width;
canvas.height = height;
// 繪製一個圓
context.beginPath(); // 開始建立路徑
context.arc(width/2,height/2,height/2-10,0,2*Math.PI,false);
context.lineWidth = 10;
context.strokeStyle="#12365a"; // 輪廓顏色
context.lineCap = "round"; // 繪製圓帽
context.stroke(); // 經過線條來繪製輪廓
context.closePath(); // 關閉路徑
// this.draw();
context.beginPath();
context.font = `${72/320}rem PingFang SC`;
context.textAlign = 'right';
context.textBaseline = 'bottom';
context.fillStyle="#00a8ff";
context.fillText('%',width/2+110,height/2+25);
context.stroke();
context.closePath();
// 繪製半圓
context.beginPath();
context.arc(width/2,height/2,height/2-10,-Math.PI/2,-Math.PI/2+i*rad,false);
context.lineWidth = 10;
// 建立漸變顏色
let linearGrad = context.createLinearGradient(0,0,width,height);
linearGrad.addColorStop(0.0, '#02a7ff');
linearGrad.addColorStop(0.25, '#1da1fb');
linearGrad.addColorStop(0.5, '#5893f4');
linearGrad.addColorStop(0.75, '#9484ec');
context.strokeStyle = linearGrad;
context.stroke();
context.closePath();
// 繪製文本信息
context.beginPath();
context.font = `${236/302}rem PingFang SC`;
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = "#00a8ff";
context.fillText(i.toFixed(0),width/2,height/2); // 繪製文本最大寬度
context.stroke();
context.closePath();
}
componentWillUnmount(){
  this.timerId && clearInterval(this.timerId);
}
render() {
return (
<div className="perent-ring-box">
<canvas className="perent-canvas" ref='ring'>
<p>請使用最新的谷歌、火狐、IE瀏覽器</p>
<p>您的瀏覽器不支持</p>
</canvas>
</div>
)
 
}
}
相關文章
相關標籤/搜索