Home > Blockchain >  How do i colour a rectangle in two colours js
How do i colour a rectangle in two colours js

Time:05-21

I have one rectangle that I want to fill with green and red, as a health bar for a game.

ctx.beginPath();
ctx.rect(this.x 5, this.y-15, 30, 3); // this.x/y are class members
ctx.strokeStyle="#000000";
ctx.lineWidth=5;
ctx.stroke();
ctx.fillStyle="green";
ctx.fill();
ctx.closePath();

Now this will give me a purely green rectangle, how can I make it so x percent of the rectangle is green and the rest is red?

CodePudding user response:

I would simply draw another rectangle on top of the red rectangle, and move the x position according to the hp.

CodePudding user response:

If you're interested in a pure HTML/CSS/JS solution, W3 Schools' How TO - JavaScript Progress Bar, is a published solution to a progress bar which is similar to what you are after.

var i = 0;
function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar");
    var width = 1;
    var id = setInterval(frame, 10);
    function frame() {
      if (width >= 100) {
        clearInterval(id);
        i = 0;
      } else {
        width  ;
        elem.style.width = width   "%";
      }
    }
  }
}
#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: green;
}
<div id="myProgress">
  <div id="myBar"></div>
</div>
<br>
<button onclick="move()">Click Me</button> 

  • Related