2012-11-27 160 views
1

說我有下面的代碼使用畫布繪製網格:畫布使線條較粗

var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'), 
    rows = 10, 
    cols = 10, 
    size = canvas.getAttribute("width")/rows; 

drawGrid(); 

function drawGrid() { 
    for (var i = 0; i < rows; i++) { 
     for (var j = 0; j < cols; j++) { 
      ctx.strokeStyle ='rgba(242, 198, 65, 0.1)'; 
      ctx.strokeRect(i * size, j * size, size, size); 
      ctx.fillStyle = 'rgb(38,38,38)'; 
      ctx.fillRect(i * size, j * size, size, size); 
     } 
    } 
} 

您可以查看結果here

我的問題是,爲什麼電網出現較厚,如果我發表意見線ctx.fillRect(i * size, j * size, size, size);

編輯

我怎樣才能得到相同的結果無線那麼使用fillRect

回答

2

您的筆畫呈現在半像素上,這會導致它們在兩個像素間模糊。你的填充覆蓋了一部分,使它們看起來再次像半像素。

簡單的解決方案是將圖形偏移0.5, 0.5以繪製整個像素。關於這方面的更多信息,請參閱http://diveintohtml5.info/canvas.html開始部分:

問:爲什麼在0.5開始x和y?爲什麼不是0?


無論如何,你不應該使用rects製作一個網格,你應該只使用線,你應該永遠只能有一次中風,到了最後,當電網完成。這樣做可以確保您的半透明網格在網格線的交點處沒有較粗的點。

下面是一個例子:

var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'), 
    rows = 10, 
    cols = 10, 
    size = canvas.width/rows, 
    width = canvas.width, 
    height = canvas.height; 
drawGrid(); 


function drawGrid() { 
    // An odd-sized lineWidth means we should translate to draw on whole pixels 
    ctx.translate(0.5, 0.5); 
    for (var i = 1; i < rows; i++) { 
     ctx.moveTo(0, i * size); 
     ctx.lineTo(width, i * size); 
    } 
    for (var j = 1; j < cols; j++) { 
     ctx.moveTo(j * size, 0); 
     ctx.lineTo(j * size, height); 
    } 
    // translate back: 
    ctx.translate(-0.5, -0.5); 
    // setting stroke style and stroking just once 
    ctx.strokeStyle = 'rgba(242, 198, 65, 0.1)'; 
    ctx.stroke(); 
} 

小提琴:http://jsfiddle.net/tZqZv/4/

1

因爲你fillRect與由strokeRect繪製的邊界重疊。

+0

如何,我可以得到不使用'fillRect'同樣的效果? –

2

渲染的筆畫跨越像素邊界。這在看起來像抗鋸齒效果的外觀中顯現出來,並且因此當填充不被應用並且不與像素邊界重疊時,該線顯得更粗。如果我們平移0.5,那麼我們不跨越像素邊界,並且觀察線條厚度是否應用填充或不填充。 Here's an example.

var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'), 
    rows = 10, 
    cols = 10, 
    size = canvas.getAttribute("width")/rows - 5; 
drawGrid(); 


function drawGrid() { 
    for (var i = 0; i < rows; i++) { 
     for (var j = 0; j < cols; j++) { 
      ctx.strokeStyle ='rgba(0, 0, 0, 1)'; 
      ctx.strokeRect(i * size + 0.5, j * size + 0.5, size, size); 
      ctx.fillStyle = 'rgb(38,128,128)'; 
      //ctx.fillRect(i * size + 0.5, j * size + 0.5, size, size); 
     } 
    } 
} 

Here's a decent reference to the effect