Как я могу создать панель загрузки градиента на холсте

#canvas #html5-canvas

#холст #html5-холст

Вопрос:

введите описание изображения здесь

Как я могу добиться этого эффекта в панели загрузки, только с помощью canvas?

Ответ №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>