var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); var x = 100, y = 100, r = 40, ringWidth = 10; var num = num1; point = 50; var range = document.getElementById('range'); var num1 = parseInt(range.value); range.onchange = function () { num1 = parseInt(range.value); move(point); }; move = function (point) { num = num1; ctx.clearRect(x - r - 5, y - r - 5, 2 * (r + 5), 2 * (r + 5)); ctx.beginPath(); ctx.fillStyle = "transparent"; ctx.arc(x, y, r + ringWidth / 2, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.fillStyle = "transparent"; ctx.arc(x, y, r - ringWidth / 2, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.lineWidth = ringWidth; var angle = 1.5 * Math.PI - point * Math.PI / 50; var leftGrad, rightGrad; if (point <= 50) { leftGrad = ctx.createLinearGradient(x, y - r, x, y + r); leftGrad.addColorStop(0.1, '#ff5151'); // 红 leftGrad.addColorStop(0.5, '#ECD806'); // 黄 leftGrad.addColorStop(1, '#dfd706'); // 黄 ctx.strokeStyle = leftGrad; ctx.arc(x, y, r, 1.5 * Math.PI, angle, true); } else if (point <= 70) { leftGrad = ctx.createLinearGradient(x, y - r, x, y + r); leftGrad.addColorStop(0.1, '#ff5151'); // 红 leftGrad.addColorStop(0.5, '#ECD806'); // 黄 leftGrad.addColorStop(0.8, '#dfd706'); // 黄 leftGrad.addColorStop(1, '#7FCF00'); //绿 ctx.beginPath(); ctx.strokeStyle = leftGrad; ctx.arc(x, y, r, 1.5 * Math.PI, 0.5 * Math.PI, true); ctx.stroke(); ctx.beginPath(); rightGrad = ctx.createLinearGradient(x, y + r + ringWidth / 2.5, x, y); rightGrad.addColorStop(0.2, '#7FCF00'); //绿 ctx.strokeStyle = rightGrad; ctx.arc(x, y, r, 0.5 * Math.PI, angle, true); } else if (point < 100) { leftGrad = ctx.createLinearGradient(x, y - r, x, y + r); leftGrad.addColorStop(0.1, '#ff5151'); // 红 leftGrad.addColorStop(0.5, '#ECD806'); // 黄 leftGrad.addColorStop(0.8, '#dfd706'); // 黄 leftGrad.addColorStop(1, '#7FCF00'); ctx.beginPath(); ctx.strokeStyle = leftGrad; ctx.arc(x, y, r, 1.5 * Math.PI, 0.5 * Math.PI, true); ctx.stroke(); ctx.beginPath(); rightGrad = ctx.createLinearGradient(x, y + r, x, y); rightGrad.addColorStop(1, '#7FCF00'); //绿 ctx.strokeStyle = rightGrad; ctx.arc(x, y, r, 0.5 * Math.PI, angle, true); } else if (point === 100) { ctx.strokeStyle = "#7FCF00"; ctx.arc(x, y, r, 0, 2 * Math.PI, true); } ctx.stroke(); if (num > point) { point++; } if (num < point) { point--; } setTimeout(function () { move(point); }, 30); }; move(point);
<canvas id="mycanvas" width=500 height=400></canvas> <input type="range" value="60" id="range" />
canvas { border: 1px solid #4c4c4c; border-radius:10px; background: #F0EFEF; }