要實現canvas動態繪制漸變色環形百分比,可以按照以下步驟進行:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
function drawProgress(percent) {
// 清除畫布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 繪制背景圓
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = "#e0e0e0";
ctx.fill();
// 繪制進度環
ctx.beginPath();
ctx.arc(x, y, radius, -0.5 * Math.PI, (2 * percent / 100 - 0.5) * Math.PI);
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "green");
ctx.strokeStyle = gradient;
ctx.lineWidth = 10;
ctx.stroke();
// 繪制百分比文字
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(percent + "%", x, y);
}
var percent = 0;
var intervalId = setInterval(function() {
drawProgress(percent);
if (percent >= 100) {
clearInterval(intervalId);
} else {
percent += 1;
}
}, 50);
這樣就可以在canvas上實現一個動態繪制漸變色環形百分比的效果了。