canvas圆环组件
<canvas id="canvas" width="300" height="200"></canvas>
let width = 300, height = 200;
let radius = '90%';
let baseColor = '#F3F6FD'
let coverColor = ['#FDEE9A', '#F76B1C']
let value = 90
let percent = (value + '').split('%')[0]
if (!isNaN(percent)) {
percent = Number(percent)
} else {
percent = 0
}
let baseLength = width > height ? height : width
let basePercent = radius.split('%')[0] / 100
let outR = (baseLength * basePercent) / 2
let innerR = outR - 6
setTimeout(() => {
baseDraw(percent)
})
function baseDraw(percent) {
if (percent > 100 || percent < 0) return
var c = $("#canvas")[0],
ctx = c.getContext('2d'),
cWidth = c.width,
cHeight = c.height,
PI = Math.PI,
sA = (Math.PI * 5) / 6
var baseRadius = PI + (PI - sA) * 2
var step = baseRadius / 100
var sE = sA + baseRadius
var baseEnd = sA + step * percent
var baseStrokeStyle
if (!Array.isArray(coverColor)) {
baseStrokeStyle = coverColor
} else {
if (coverColor.length == 2) {
const arrList = gradient(coverColor[0], coverColor[1], 100)
var grd = ctx.createLinearGradient(0, 0, (PI * innerR * 2 * 3) / 4, 0)
grd.addColorStop(0, arrList[0])
grd.addColorStop(1, arrList[parseInt(percent) > 0 ? parseInt(percent) - 1 : 0])
baseStrokeStyle = grd
}
}
drawCanvas(ctx, cWidth / 2, (cHeight * 3) / 4, outR, sA, sE, baseColor, 2)
drawCanvas(ctx, cWidth / 2, (cHeight * 3) / 4, innerR, sA, sE, baseColor, 1, 'dashed')
if (percent != 0) {
drawCanvas(ctx, cWidth / 2, (cHeight * 3) / 4, outR, sA, baseEnd, baseStrokeStyle, 2)
drawCanvas(ctx, cWidth / 2, (cHeight * 3) / 4, innerR, sA, baseEnd, baseStrokeStyle, 1, 'dashed')
var angle = 2 * PI - baseEnd
var xPos = Math.cos(angle) * outR + cWidth / 2
var yPos = -Math.sin(angle) * outR + (cHeight * 3) / 4
drawCanvas(ctx, xPos, yPos, 1, 0, 2 * PI, baseEnd, 1)
}
}
function drawCanvas(ctx, x, y, r, sAngle, eAngle, color, lineWidth, lineStyle = 'solid') {
ctx.beginPath()
ctx.lineCap = 'round'
ctx.strokeStyle = color
ctx.lineWidth = lineWidth
ctx.setLineDash(lineStyle == 'dashed' ? [3] : [])
ctx.arc(x, y, r, sAngle, eAngle, false)
ctx.stroke()
}
function gradient(startColor, endColor, step) {
var sColor = hexToRgb(startColor),
eColor = hexToRgb(endColor)
var rStep = (eColor[0] - sColor[0]) / step,
gStep = (eColor[1] - sColor[1]) / step,
bStep = (eColor[2] - sColor[2]) / step
var gradientColorArr = []
for (var i = 0; i < step; i++) {
gradientColorArr.push(rgbToHex(parseInt(rStep * i + sColor[0]), parseInt(gStep * i + sColor[1]), parseInt(bStep * i + sColor[2])))
}
return gradientColorArr
}
function rgbToHex(r, g, b) {
var hex = ((r << 16) | (g << 8) | b).toString(16)
return '#' + new Array(Math.abs(hex.length - 7)).join('0') + hex
}
function hexToRgb(hex) {
var rgb = []
for (var i = 1; i < 7; i += 2) {
rgb.push(parseInt('0x' + hex.slice(i, i + 2)))
}
return rgb
}