簡體   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