[英]Canvas isn't updating
我打算用JavaScript
制作個人項目,直到遇到問題。 我有一個代表HP的畫布,但是它沒有更新,我嘗試了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()"/>
在punch
函數內調用hp
函數:
function punch() {
health -= 1;
hp();
}
您還需要先清除畫布,然后再添加一個較小的矩形,因此請在hp
函數中添加對畫布clearRect
方法的調用:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.