使用canvas绘制多根渐变色直线
HTML
<div class="GradualSuspense">
<div class="TotalVolume" ref="TotalVolume">
<canvas id="canvas" class="canvas" ref="myCanvas"></canvas>
</div>
</div>
绘制圆环形线条
// 绘制渐变环形进度条
const drawGradualSuspense = () => {
if (!ctx.value) {
return
}
ctx.value.save()
ctx.value.translate(myCanvas.value.width / 2, myCanvas.value.width / 2)
for (let j = 0; j < 12; j++) {
ctx.value.rotate(Math.PI * 2 / 12)
ctx.value.lineWidth = 3
ctx.value.beginPath()
ctx.value.strokeStyle = gradient('#26faf4', '#0073b9', 12)[j];
ctx.value.moveTo(0, -130)
ctx.value.lineTo(0, -100)
ctx.value.stroke()
}
ctx.value.restore()
}
将颜色转换为RGB值
function hexToRgb(hex) {
// 移除可能存在的前缀 #
hex = hex.replace(/^#/, '');
// 每个颜色分量占两位
const bigint = parseInt(hex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255
};
}
计算渐变颜色
function gradient(startColor, endColor, step) {
const startRgb = hexToRgb(startColor);
const endRgb = hexToRgb(endColor);
const colors = [];
for (let i = 0; i < step; i++) {
const t = i / (step - 1); // 计算当前步骤的比例
const r = Math.round(startRgb.r + t * (endRgb.r - startRgb.r));
const g = Math.round(startRgb.g + t * (endRgb.g - startRgb.g));
const b = Math.round(startRgb.b + t * (endRgb.b - startRgb.b));
colors.push(`rgb(${r}, ${g}, ${b})`);
}
return colors;
}