HTML Canvas 不更新
HTML Canvas doesn't update
当我调用 move() 时,"y" 变量发生了变化,但框仍呈现在同一位置。
var c = document.getElementById("can"); //my canvas id is "can"
var pen = c.getContext("2d");
var y = 200;
setInterval(render(y), 1000/30); //update 30 times per second
function move(dir){
y=y+dir;
}
function render(height) {
pen.beginPath();
pen.clearRect(0,0,888,500);
pen.beginPath();
pen.rect(30,height,50,50); //Draw the player
pen.fillStyle="green";
pen.fill();
}
因为你的函数 move() 永远不会 used.It 如果你改变它的高度或宽度就可以更新:)
您必须在 setInterval 中调用 move
和 render
。
var c = document.getElementById("can"); //my canvas id is "can"
var pen = c.getContext("2d");
var y = 0;
var dir = 20;
function dirValue(val) {
dir = val;
}
setInterval(function() {
move(dir);
render(y);
}, 1000); //update 30 times per second
function move(dir) {
return y = y + dir;
}
function render(height) {
//console.log(height);
pen.beginPath();
pen.clearRect(0, 0, 888, 500);
pen.beginPath();
pen.rect(30, height, 50, 50); //Draw the player
pen.fillStyle = "green";
pen.fill();
}
<button type='button' onclick='dirValue(20)'>Down</button>
<button type='button' onclick='dirValue(-20)'>UP</button>
<button type='button' onclick='dirValue(0)'>Stop</button>
<canvas id="can" width="1000" height="1000"></canvas>
当我调用 move() 时,"y" 变量发生了变化,但框仍呈现在同一位置。
var c = document.getElementById("can"); //my canvas id is "can"
var pen = c.getContext("2d");
var y = 200;
setInterval(render(y), 1000/30); //update 30 times per second
function move(dir){
y=y+dir;
}
function render(height) {
pen.beginPath();
pen.clearRect(0,0,888,500);
pen.beginPath();
pen.rect(30,height,50,50); //Draw the player
pen.fillStyle="green";
pen.fill();
}
因为你的函数 move() 永远不会 used.It 如果你改变它的高度或宽度就可以更新:)
您必须在 setInterval 中调用 move
和 render
。
var c = document.getElementById("can"); //my canvas id is "can"
var pen = c.getContext("2d");
var y = 0;
var dir = 20;
function dirValue(val) {
dir = val;
}
setInterval(function() {
move(dir);
render(y);
}, 1000); //update 30 times per second
function move(dir) {
return y = y + dir;
}
function render(height) {
//console.log(height);
pen.beginPath();
pen.clearRect(0, 0, 888, 500);
pen.beginPath();
pen.rect(30, height, 50, 50); //Draw the player
pen.fillStyle = "green";
pen.fill();
}
<button type='button' onclick='dirValue(20)'>Down</button>
<button type='button' onclick='dirValue(-20)'>UP</button>
<button type='button' onclick='dirValue(0)'>Stop</button>
<canvas id="can" width="1000" height="1000"></canvas>