health bar
by andersand
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/victor/1.1.0/victor.min.js"></script>
<canvas width="400" height="300" id="can"></canvas>
<div>
<label>pos: </label><label id="posx"></label><br />
<label>poy: </label><label id="poy"></label><br />
</div>
CSS
body {
background-color: #242623;
margin: 0;
padding: 0;
}
canvas {
background-color: #333;
cursor: crosshair;
}
div {
position: absolute;
top: 0;
left: 0;
display: none;
}
JavaScript
const can = document.getElementById("can")
const ctx = can.getContext("2d")
const pi2 = Math.PI * 2
const speed = 20
const maxHealth = 100
let health = 100
let r = 20
let cpoint = new Victor(200, 200)
plot()
function plot() {
ctx.clearRect(0, 0, 400, 300) // clr canvas
drawBullet(cpoint, "red")
drawHealthBar(cpoint)
setTimeout(plot, speed)
}
function drawHealthBar(vec) {
ctx.fillStyle = "#000"
ctx.fillRect(vec.x-maxHealth/2, vec.y + r + 4, maxHealth, 4)
let clr = health > 60 ? "#0f0" : (health > 30 ? "#ff0" : "#f00")
ctx.fillStyle = clr
ctx.fillRect(vec.x-maxHealth/2, vec.y + r + 4, health, 4)
}
function showInfo(pox, posy) {
document.querySelector("#posx").innerHTML = pox
document.querySelector("#posy").innerHTML = posy
}
can.addEventListener("mousedown", function(ev) {
if (health > 0) {
health -= 10
}
})
function drawBullet(point, color) {
ctx.fillStyle = color
ctx.beginPath()
ctx.ellipse(point.x, point.y, r, r, 0, 0, pi2)
ctx.fill()
}