Learn Create Your Own Split Screen

Next Page

We'll add a variable that represents the health of the jelly, and start it at 100 for full health
var health = 100; // jelly health starts at 100
We'll create a function that makes our jelly health diminish, but never to less than zero
function Diminish_Health() { if (health > 0) health= health - 1; // health drops, but never past zero }
And we'll have that function called every 250ms, in other words, four times per second.
setInterval(Diminish_Health, 250); // lose health slowly but surely
Every time we eat a fish, just next to where we add one to the score, we'll also boost the health by 10. But it will never go above 100.
health= health + 10; // eating a fish regains health if (health > 100) health= 100; // but never past 100
Finally, we'll display the health on the canvas every time we Do_a_frame. But instead of displaying it as a number, we'll show it as a little bar graph. It'll have a black border (stroke) and a filled centre that's green when everything is good, but turns red when the health drops below 30.

Sounds complicated, but four lines of code take care of it using the rectangle skills you learned earlier.

ctx.fillStyle= "green"; // assume all is fine, colour will be green if (health < 30) ctx.fillStyle= "red"; // if health is low, colour will be red ctx.fillRect(myCanvas.width-110, 5, health, 10); // fill a rectangle whose width is my health ctx.strokeRect(myCanvas.width-110, 5, 100, 10); // stroke a border, full width (default strokecolor is black)