当前位置:   article > 正文

用初中数学知识撸一个canvas环形进度条,熬夜整理小米前端面试题

用初中数学知识撸一个canvas环形进度条,熬夜整理小米前端面试题

ctx.textAlign = ‘center’

ctx.textBaseline = ‘middle’

ctx.fillText(this.label, canvas.clientWidth / 2, canvas.clientWidth / 2);

}

画文字

画进度弧


支持普通颜色和渐变色withGradient默认为true,代表使用渐变色绘制进度弧,渐变方向我默认给的从上到下。如果希望使用普通颜色,withGradientfalse即可,并可以通过lineColor自定义颜色。

if (this.withGradient) {

this.gradient = ctx.createLinearGradient(this.circleRadius, 0, this.circleRadius, this.circleRadius * 2);

this.lineColorStops.forEach(item => {

this.gradient.addColorStop(item.percent, item.color);

});

}

其中lineColorStops是渐变色的颜色偏移断点,由父组件传入,可传入任意个颜色断点,格式如下:

colorStops2: [

{ percent: 0, color: ‘#FF9933’ },

{ percent: 1, color: ‘#FF4949’ }

]

画一条从上到下的进度弧,即270°90°

ctx.strokeStyle = this.withGradient ? this.gradient : this.lineColor;

ctx.lineWidth = this.lineWidth;

ctx.beginPath();

ctx.arc(this.outerRadius, this.outerRadius, this.circleRadius, this.deg2Arc(270), this.deg2Arc(90));

ctx.stroke();

画进度弧

其中lineWidth是弧线的宽度,由父组件传入

lineWidth: {

type: Number,

default: 8

}

画进度圆点


最后我们需要把进度圆点补上,我们先写死一个角度90°,显而易见,圆点坐标为(this.outerRadius, this.outerRadius + this.circleRadius)

90度圆点坐标

画圆点的代码如下:

ctx.fillStyle = this.pointColor;

ctx.beginPath();

ctx.arc(this.outerRadius, this.outerRadius + this.circleRadius, this.pointRadius, 0, this.deg2Arc(360));

ctx.fill();

其中pointRadius是圆点的半径,由父组件传入:

pointRadius: {

type: Number,

default: 6

}

90度画圆点

角度自定义


当然,进度条的角度是灵活定义的,包括开始角度,结束角度,都应该由调用者随意给出。因此我们再定义一个属性angleRange,用于接收起止角度。

angleRange: {

type: Array,

default: function() {

return [270, 90]

}

}

有了这个属性,我们就可以随意地画进度弧和圆点了,哈哈哈哈。

等等,你忘了这个场景

老哥,这种圆点坐标怎么求?

特殊角度怎么求圆点圆心坐标

噗…看来高兴过早了,最重要的是根据不同角度求得圆点的圆心坐标,这让我顿时犯了难。

你要冷静

经过冷静思考,我脑子里闪过了一个利用正余弦公式求坐标的思路,但前提是坐标系原点如果在圆环外接矩形的左上角才好算。仔细想想,冇问题啦,我先给坐标系平移一下,最后求出来结果,再补个平移差值不就行了嘛。

平移坐标系后求圆点坐标

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/380856?site
推荐阅读
相关标签