2015-09-25 29 views
0

當我添加ctx.addEventListener使得畫布繪製消失

ctx.addEventListener('mousedown', onDown, false); 

畫布繪製(背景和形狀)消失,頁面是空白的,然後當我刪除他們又重新出現在代碼此事件偵聽器。只是想知道爲什麼會發生這種情況?在此先感謝

<script> 


var ctx, W, H; 
var x = 10; 

window.onload = function() { 


    var canvas = document.getElementById("canvas"); 
    W = window.innerWidth; 
    H = window.innerHeight; 
    canvas.width = W; 
    canvas.height = H; 


    ctx = canvas.getContext("2d"); 
    ctx.addEventListener('mousedown', onDown, false); //When this is here, canvas drawing disappears, when it's not here canvas drawing reappears again 




    setInterval(draw, 1); 


function draw() { 
    ctx.globalCompositeOperation = "source-over"; 
    ctx.fillStyle = "#E6E6FF"; 
    ctx.fillRect(0, 0, W, H); 

    ctx.fillStyle = "black"; 
    ctx.fillRect(x,20,10,10); 
    ctx.font = "30px Arial"; 
    ctx.fillText("Hello World",10,80); 
    ctx.fill(); 

} 


} 


function onDown(event) { 
    //where x is found 
    cx = event.pageX 
    cy = event.pageY 
    alert("X,Y ="+cx+','+cy); 
} 
+0

請檢查控制檯是否有錯誤,注意它會說'ctx.addEventListener不是函數'。 –

回答

1

您不能將事件偵聽器添加到畫布的上下文。您需要將其添加到畫布本身。

代替:

ctx.addEventListener('mousedown', onDown, false); 

&hellip;做到這一點:

canvas.addEventListener('mousedown', onDown, false); 
1

jsBin demo

使用:

ctx.canvas.addEventListener 

或:

canvas.addEventListener 

原因context就是一個對象,其中HTMLE 。lementCanvas住在

要發現這樣的錯誤你的自我,最簡單的方法是使用開發工具來調試代碼,打開控制檯標籤和閱讀你顯示的錯誤:

enter image description here