我计划用JavaScript
制作个人项目,直到遇到问题为止。我有一张代表惠普的画布
但它没有更新,我尝试了Intervals但它也没有用。
以下代码:
<script>
var health=100;
var h = health;
var totalhealth=100;
var intNumber;
function hp(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.2,"#F4710E");
grd.addColorStop(1,"green");
ctx.fillStyle=grd;
ctx.fillRect(0,0,(h/100)*140,10);
document.getElementById("demo").innerHTML = h +"/"+totalhealth;
}
function punch(){
health-=1;
}
</script>
HTML代码,以onload="hp()"
<canvas id="myCanvas" width="140" height="10" style="border:2px solid #000000;"></canvas>
<p id="demo"></p>
<input type="button" value="Punch" onclick="punch()"/>
答案 0 :(得分:0)
调用hp
函数中的punch
函数:
function punch() {
health -= 1;
hp();
}
您还需要在添加较小的矩形之前清除画布,因此在clearRect
函数中添加对canvas hp
方法的调用:
function hp() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "red");
grd.addColorStop(0.2, "#F4710E");
grd.addColorStop(1, "green");
ctx.fillStyle = grd;
ctx.clearRect(0, 0, c.width, c.height); //<-- this
ctx.fillRect(0, 0, (health / 100) * 140, 10); //h changed to health
document.getElementById("demo").innerHTML = health + "/" + totalhealth; //h changed to health
}
hp(); //put this in the onload function, to initialize the health bar