在我從Python的基礎知識(在Coursera RICE課程中學習)轉換到Javascript的過程中,我嘗試使用相同的範例註冊甚至處理程序,這裏的人幫助我成功轉換。使用JS和Canvas註冊事件處理程序
在這個例子中,兩個定時器和更新的處理程序沒有運行:
//Globals
var message = "test message";
var positionX = 50;
var positionY = 50;
width = 500;
height = 500;
var interval = 2000;
//handler for text box
function update(text) {
message = text;
}
//handler for timer
function tick() {
var x = Math.floor(Math.random() * (width - 0) + 0);
var y = Math.floor(Math.random() * (height - 0) + 0);
positionX = x;
positionY = y;
}
//handler to draw on canvas
function draw(canvas) {
ctx.font="20px Georgia";
ctx.fillText(message,positionX,positionY);
}
//create a frame
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
//register event handlers
setInterval(tick, interval);
draw();
//start the frame and animation
<html>
<head>
</head>
<body>
Enter text here :
<input type="text" onblur="update(this.value)">
<canvas id="myCanvas" style="border:1px solid #000000;"></canvas>
<script>
</script>
</body>
</html>
添加canvas.addEventListener("draw", draw(), false);
和canvas.addEventListener("update", update(), false);
沒有任何改變。
雖然它「工作」的唯一時間是當我在tick();
函數中添加draw();
函數時,但它保留文本並隨機地將其複製到屏幕上,因爲函數應該工作。
在一般筆記,你們覺得目前的模式:
//Global state
//Handler for text box
//Handler for timer
//Handler to draw on canvas
//Create a frame
//Register event handlers
//Start the frame animation
是值得JS和Canvas追求?
再次感謝您的時間和幫助。
K.
感謝很多盲人,其實我只添加'畫(),然後你的第一個建議。寬度,ctx.canvas.height);'tick();'函數內部的方法,它完美的工作! – xGLUEx