user1433479
user1433479

Reputation: 135

Partially filling a rectangle in HTML5

I have a canvas in which I want to draw multiple rectangles (of varying sizes). These rectangles have to be filled or emptied over time, be it automatically or by input from the user.

The problem is that I have never programmed HTML5 before and don't know how to partially fill a rectangle or increase the fill (through something like rectangle.backgroundHeight++).

Here is my code:

<canvas id="myCanvas" height="1000" width="1000" />

<script>
window.addEventListener('load', function () {
var ctx = document.getElementById('myCanvas').getContext('2d');

var interval = setInterval(function() {

  return function () {
    // Draw large fuel tanks
    var fuelA = ctx.rect(150, 60, 110, 130);
    var fuelB = ctx.rect(600, 60, 110, 130);

    // Draw small fuel tanks
    var fuelC = ctx.rect(40, 300, 60, 130);
    var fuelD = ctx.rect(300, 300, 60, 130);
    var fuelE = ctx.rect(500, 300, 60, 130);
    var fuelF = ctx.rect(750, 300, 60, 130);


    ctx.stroke();
  };
}(), 1000/25);
}, false);

Upvotes: 0

Views: 2655

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

While programming the canvas is a great skill to have, an animation like this can be done completely in CSS, using transitions:

var liquid= document.querySelector('.liquid');

document.querySelector('#bfill').onclick= function() {
  liquid.style.height = '100%';
};

document.querySelector('#bempty').onclick= function() {
  liquid.style.height = '0%';
};
.tank {
  position: absolute;
  left: 20px;
  top: 40px;
  height: 100px;
  width: 50px;
  border: 1px solid black;
}

.liquid {
  transition: height 3s;
  position: absolute;
  left: 0px;
  bottom: 0px;
  height: 20%;
  width: 100%;
  background: blue;
}
<button id="bfill">Fill the tank</button>
<button id="bempty">Empty the tank</button>
<div class="tank">
  <div class="liquid"></div>
</div>

Upvotes: 2

meskobalazs
meskobalazs

Reputation: 16041

I do not think that is possible by using one rectangle, as it can only be filled by a single color, or a gradient - and there is no option for partial fill.

However you may draw a rectangle with only strokes and no fill, and another on top of it, which acts as a fill for the first rectangle. You can size this however you want to.

Edit: Well it seems, you can achieve this with gradients, however I can't really tell which is the better solution.

Upvotes: 1

chead23
chead23

Reputation: 1879

You could use a gradient to get an effect of partially filling e.g filling a rectangle 50%.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var rec = ctx.rect(20, 20, 150, 100);
var grd = ctx.createLinearGradient(0, 0, 190, 0);
grd.addColorStop(0, "black");
grd.addColorStop(0.5, "black");
grd.addColorStop(0.5, "white");
grd.addColorStop(1, "white");

ctx.fillStyle = grd;
ctx.fill();

ctx.strokeStyle = 'black';
ctx.stroke();
<canvas id="myCanvas" />

Upvotes: 1

Related Questions