2011-12-03 26 views
0

我目前在畫布上使用fillRect方法,像這樣設置各個像素的循環中:在canavs的imageData設置一個像素對於給定的X和Y

context.fillStyle = "rgba("+colourR+","+colourG+","+colourB+",255)"; 
context.fillRect(x, y, 1, 1) 

這種方法效果很好,但它,和putImageData,是非常緩慢的。所以我決定嘗試和內環路單獨設置的像素,然後使用putImageData一個呼叫時準備輸出到屏幕上,就像這樣:

var screenImageData = context.getImageData(0,0,800,600); 
var pixelBuffer = screenImageData.data;  
pixelBuffer[(x*4) + (y*(screenImageData.width * 4))] = colourR; 
pixelBuffer[(x*4) + (y*(screenImageData.width * 4)) + 1] = colourG; 
pixelBuffer[(x*4) + (y*(screenImageData.width * 4)) + 2] = colourB; 
pixelBuffer[(x*4) + (y*(screenImageData.width * 4)) + 3] = 255; 

... 

context.putImageData(screenImageData,0,0); 

然而,這會產生一個完全不同的輸出fillRect方法(它看起來像混亂垃圾)。我在這裏做錯了什麼?

+0

爲什麼在這種情況下您需要使用getImageData()和putImageData()? – anson

+0

你可以把測試用具放在什麼地方嗎? – Nickolay

+0

你爲什麼要做'screenImageData.width * 4'? –

回答

0

這裏的問題在於x和y的計算方式,顯然putImageData將它們自動轉換爲整數。在它們上使用Math.floor是所有必需的。

相關問題