繁体   English   中英

如何使HTML5画布进度栏从下至上而不是从上至下填充?

[英]How can I make this HTML5 canvas progress bar fill from the bottom up instead of the top down?

我使用此示例构建自己的进度条,该进度条将跟踪我正在制作的游戏中玩家的燃料水平。

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;
}

问题

我需要它从底部向上填充而不是顶部向下填充。 我该如何实现? 我尝试过旋转画布,但似乎无法使其正常工作。

如果我已经理解了您的问题,那么您需要做的就是以较低(即较大)的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);
  }
}
...

和一些小提琴

记录下来,这只是除了摩根的答案之外的另一种选择。 它可以让您从上到下进行填充,但从下到上进行渲染:

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

分叉的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM