如何从底部向上而不是自上而下填充此HTML5画布进度条?

时间:2015-05-04 22:14:54

标签: javascript css html5 canvas 2d

我正在使用this example建立我自己的进度条,以便在我正在制作的游戏中跟踪玩家的燃油水平。

HTML

<h1>Canvas Progress Bar Test</h1>
<form>
  <ul>
    <li>
      <input type="radio" name="direction" id="vertical" value="vertical" checked />
      <label for="vertical">Vertical</label>
      <input type="radio" name="direction" id="horizontal" value="horizontal" />
      <label for="horizontal">Horizontal</label>
    </li>

    <li>
      <label for="width">Width</label>
      <input type="number" id="width" value="20" />
    </li>
    <li>
      <label for="height">Height</label>
      <input id="height" type="number" value="200" />
    </li>
    <li>
      <label for="max">Max Value</label>
      <input id="max" type="number" value="100" />
    </li>
    <li>
      <label for="val">Value</label>
      <input id="val" type="number" value="20" />
    </li>
    <li>
      <input id="submit" type="submit" />
    </li>
  </ul>
</form>

<canvas id="canvas" width="500" height="500"><canvas>

JS

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

function drawScrollbar () {
  var width = parseInt($('#width').val()),
    height = parseInt($('#height').val()),
    max = parseInt($('#max').val()),
    val = Math.min(Math.max(parseInt(parseInt($('#val').val())), 0), max),
    direction = $('input[name="direction"]:checked').val();

  // Draw the background
  ctx.fillStyle = '#000';
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(0, 0, width, height);

  // Draw the fill
  ctx.fillStyle = '#777';
  var fillVal = Math.min(Math.max(val / max, 0), 1);
  if (direction === 'vertical') {
    ctx.fillRect(0, 0, width, fillVal * height);
  } else {
    ctx.fillRect(0, 0, fillVal * width, height);
  }
}

drawScrollbar();

$('#submit').click(function (e) {
  e.preventDefault();
  drawScrollbar();
});

CSS

h1 {
  font-size: 20px;
  margin: 5px 5px 10px;
}

input[type="number"], li {
  display: block;
  margin-bottom: 10px;
}

form {
  margin: 5px;
}

canvas {
  padding: 20px;
}

问题

我需要它从底部填充而不是顶部向下填充。我怎样才能做到这一点?我试过旋转画布,但我似乎无法让它工作。

2 个答案:

答案 0 :(得分:2)

如果我理解了您的问题,您需要做的是开始在较低(即较大)的y值下绘制矩形。更具体地说,在height - (fillVal * height)

以下是调整方法

...
// Draw the fill
  ctx.fillStyle = '#777';
  var fillVal = Math.min(Math.max(val / max, 0), 1);
  if (direction === 'vertical') {
    ctx.fillRect(0, height - (fillVal * height), width, fillVal * height);
  } else {
    ctx.fillRect(0, 0, fillVal * width, height);
  }
}
...

和一点fiddle

答案 1 :(得分:2)

除了摩根的答案之外,这只是另一种方法。它将允许您从上到下填充,但它将从下到上呈现:

ctx.setTransform(1, 0, 0, -1, 0, height);     // reverses the coordinate system's y-axis
ctx.fillRect(0, 0, width, fillVal * height);  // fill as you would top to bottom
ctx.setTransform(1, 0, 0, 1, 0, 0);           // reset transforms

<强> Forked fiddle