答案 0 :(得分:1)
您可以使用context.createLinearGradient创建线性渐变。
然后随着任务的进行,您可以填充指示进度的(渐变)矩形。
// clear the previous progress bar
context.clearRect(x0,y0,x0+width,y0+height);
// canvas related vars
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// define the area of the progress bar
var x0 = 50;
var y0 = 50;
var width = 100;
var height = 10;
// Example: redraw progress bar at 85% complete
redrawProgress(0.85);
// clear the previous progress bar an redraw the current progress
function redrawProgress(pct) {
// create a linear gradient in the area of the progress bar
var gradient = context.createLinearGradient(x0, y0, x0 + width, y0)
gradient.addColorStop(0.00, 'green');
gradient.addColorStop(1.00, 'red');
// clear the previous progress bar
context.clearRect(x0, y0, x0 + width, y0 + height);
// set your current progress
pct = 0.85;
// re-fill the progress bar with the current progress
context.fillStyle = gradient;
context.fillRect(x0, y0, width * pct, height);
// outline the full progress bar
context.strokeStyle = 'black';
context.strokeRect(x0, y0, width, height);
}
<canvas id='canvas' width=300 height=200></canvas>