2012-07-05 74 views
2

我用canvas元素玩過,下面的代碼在沒有變換的情況下可以正常工作,但是當我將變換放入時,紅框會在其後面繪製一個「尾部」。奇怪的是,尾巴的顏色與盒子的顏色不同,它也不同於瀏覽器和瀏覽器(在FF中更暗)。 這是正常的嗎?我想這是由於四捨五入。畫布上的變換導致奇怪的行爲

function draw() { 
var canvas = document.getElementById("canvas"); 
g = canvas.getContext("2d"); 

var x = 0; 
var y = 200; 
g.transform(.5,0,0,1,0,0); 
g.fillStyle = "rgb(200,0,0)"; 
timer = setInterval(function() { 
    if(x == 750) clearInterval(timer); 
    g.clearRect(x,y,50,50); 
    x ++; 
    g.fillStyle = "rgb(200,0,0)"; 
    g.fillRect(x,y,50,50); 
}, 10); 
} 
<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript" src="test.js"></script> 
</head> 
<body onload="draw()"> 
    <canvas id="canvas" width="800" height="600"></canvas> 
</body> 
</html> 
+0

btw。變換(.5,0,0,1,0,0)與比例(0.5,1)相同。嘗試縮放(0.99,1)以獲得有趣的效果。 – SpiderPig 2012-07-05 19:48:18

回答

0

縮放被applyed到clearRect爲好。在每次調用setInterval回調函數時,由於X值仍然相同,因此0123'完全覆蓋了最後繪製的矩形,但是當您調用fillRect以再次繪製紅色矩形時,X值爲由於你的X軸被縮放了0.5(半個像素),在偶數值處它需要另一個像素,但是在奇數值時它應該採取「半個像素」,因爲那不存在兩種顏色的像素(白色和紅色)進行混合以試圖獲得平滑效果,因爲兩種顏色都應該在每個像素的一半上。我想大多數情況下都是好的,但在這種情況下,它不是。

So let x be 2 (forget about the y axis here, kay?) 
Have a rect from x to x+50 (transformed coords are 1, 26) 
Clear rect from x to x+50 (1, 26) 

We end up here with a white rect from 1 to 26, right? 

add 1 to x 
Have a rect from x to x+50 (1.5, 26.5) 

Oops, there's no such pixel 1.5, 1 it is. 
Pixel one is filled with white already, nobody ordered me to clear that but I have to fill with red this same pixel. 

Solution = blend colors 

呀,所以你看到的尾巴是充滿紅+白,不完全白desapear,也不是完全的紅色與矩形的其餘部分混合像素的1列的結果。

一個解決辦法是:

g.clearRect(x-1,y,50,50); 

使用x-1你就可以趕上像素此列。

希望我很清楚。

我認爲音色的差異是由於在每個瀏覽器中實現混合的差異,但我總是注意到,根據瀏覽器的不同,相同顏色的色調不僅在畫布上的應用。