2011-09-28 143 views
0

我最近一直與HTML 5和具體畫布對象經歷過了第一時間後的HTML 5畫布的緩慢更新。問題與鼠標移動/鼠標點擊事件

我似乎有與鼠標事件的一些問題。

該方案是具有不同顏色的背景面的網格隨機變化。上面有一個雲形狀,我用它作爲剪輯區域,只能看到雲下的網格部分。 (想想形狀奇特炬光)

的問題是,我試圖用鼠標移動雲區,它不與任何鼠標移動或鼠標點擊事件順利更新。似乎需要一兩個框架才能跟上,而單車顏色似乎還在繼續。

我曾嘗試:

  • 取出隨機顏色的加速。
  • 僅使用簡單的形狀進行裁剪。
  • 設置setInterval函數來更新每1ms

可以看出這裏運行 - http://jsfiddle.net/mXrNk/14/

任何幫助,將不勝感激。可能丟失了一些明顯的東西。

<script> 

const FPS = 60; 
var myimg = new Image(); 

window.addEventListener('click', clicked, true); 

var mouseX = 170; 
var mouseY = 80; 

window.onload = init; 

function init() { 

    canvas = document.getElementById('myCanvas'); 
    context = canvas.getContext('2d'); 

    myimg.src = "smile.png"; 

    setInterval(draw, 1000/FPS); 

} 

function draw() { 

    context.clearRect(0,0,canvas.width,canvas.height); 
    // draw cloud 
    context.beginPath(); // begin custom shape 
    context.moveTo(mouseX, mouseY); 
    context.bezierCurveTo(mouseX-40, mouseY+20, mouseX-40, mouseY+70, mouseX+60, mouseY+70); 
    context.bezierCurveTo(mouseX+80, mouseY+100, mouseX+150, mouseY+100, mouseX+170, mouseY+70); 
    context.bezierCurveTo(mouseX+250, mouseY+70, mouseX+250, mouseY+40, mouseX+220, mouseY+20); 
    context.bezierCurveTo(mouseX+260, mouseY-40, mouseX+200, mouseY-50, mouseX+170, mouseY-30); 
    context.bezierCurveTo(mouseX+150, mouseY-75, mouseX+80, mouseY-60, mouseX+80, mouseY-30); 
    context.bezierCurveTo(mouseX+30, mouseY-75, mouseX-20, mouseY-60, mouseX, mouseY); 
    context.closePath(); // complete custom shape 
    context.lineWidth = 5; 
    context.strokeStyle = "#0000ff"; 
    context.stroke(); 

    context.save(); 
    context.clip(); 

    for (i = 0; i<7; i++) { 
     for (j = 0; j < 13; j++) { 
      context.strokeRect(j*myimg.width, i*myimg.height, myimg.width, myimg.height); 
      context.fillStyle = rndColor(); 
      context.fillRect(j*myimg.width, i*myimg.height, myimg.width, myimg.height); 
      context.drawImage(myimg, j*myimg.width, i*myimg.height); 
      context.fillStyle = "black"; 
      context.font = "italic 10pt Arial "; 
      context.fillText((i*13)+j, j*myimg.width+5,i*myimg.width+15); 
     } 
    } 

    context.restore(); 

} 

function rndColor() { 
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6); 
} 

function clicked(e) { 
    mouseX = e.pageX; 
    mouseY = e.pageY; 
} 

</script> 
+0

小提琴殺死鉻糟糕! – Loktar

回答

3

Live Demo

我用setTimeout而非setInterval。如果在它完成之前嘗試運行該函數時使用間隔,那麼這些事件將會建立起來,並且在呼叫仍在建立時仍然繼續嘗試運行。

超時但只會調用該函數一次,那麼你可以設置其他超時在函數的底部再次調用自身。這樣做可以確保功能已完成,並且不會導致等待處理的呼叫累積。

也看看這篇文章,

https://simonsarris.com/increasing-performance-by-caching-paths-on-canvas/

其對緩存的路徑。它實際上由我打賭會彈出並看到這個問題的Simon Sarris。

+0

非常感謝。就像我打算現在:) – Volv

+0

沒有問題很高興有幫助。 – Loktar

+0

那個鏈接是404:'( –