2013-01-19 66 views
0

我需要做一個矩形與路徑(因爲我想要一些邊緣是另一種顏色,例如或另一種線條類型點綴左右..),不重疊(所以當我設置0.5到0.5的一些邊緣不會因爲重疊而變暗)與畫布2d。如何創建一個具有填充和筆劃的路徑並且筆劃在alpha <1時不重疊?

我已經試過的linecap做到這一點,但它在阿爾法重疊...

檢查我所做的事情,但並不好。 http://jsfiddle.net/kLZfc/6/

只有3px的作品,用1px的不...

var ctx = document.querySelector('canvas').getContext('2d'); 
var offset; 

offset = 10.5; 
ctx.lineWidth = 3; 
ctx.globalAlpha = 0.5 
ctx.beginPath(); 
ctx.strokeStyle = 'red'; 
ctx.lineTo(offset, offset); 
ctx.lineTo(offset + 10, offset); 
ctx.lineTo(offset + 10, offset + 10); 
ctx.lineTo(offset, offset + 10); 
ctx.lineTo(offset, offset); 
ctx.stroke(); 



offset = 25.5; 
ctx.lineWidth = 3; 
ctx.globalAlpha = 0.5 
ctx.beginPath(); 
ctx.strokeStyle = 'red'; 
ctx.lineTo(offset, offset); 
ctx.lineTo(offset + 10, offset); 
ctx.lineTo(offset + 10, offset + 10); 
ctx.lineTo(offset, offset + 10); 
ctx.lineTo(offset, offset); 
ctx.closePath(); 
ctx.stroke(); 



offset = 40.5; 
ctx.lineWidth = 1; 
ctx.globalAlpha = 0.5 
ctx.beginPath(); 
ctx.strokeStyle = 'red'; 
ctx.lineTo(offset, offset); 
ctx.lineTo(offset + 10, offset); 
ctx.lineTo(offset + 10, offset + 10); 
ctx.lineTo(offset, offset + 10); 
ctx.lineTo(offset, offset); 
ctx.closePath(); 
ctx.stroke(); 



offset = 55.5; 
ctx.lineWidth = 1; 
ctx.globalAlpha = 0.5 
ctx.beginPath(); 
ctx.strokeStyle = 'red'; 
ctx.lineTo(offset, offset); 
ctx.lineTo(offset + 10, offset); 
ctx.lineTo(offset + 10, offset + 10); 
ctx.lineTo(offset, offset + 10); 
ctx.lineTo(offset, offset); 
ctx.stroke(); 



offset = 70.5; 
ctx.lineWidth = 1; 
ctx.lineCap = "square"; 
ctx.globalAlpha = 0.5 
ctx.beginPath(); 
ctx.strokeStyle = 'red'; 
ctx.lineTo(offset, offset); 
ctx.lineTo(offset + 10, offset); 
ctx.lineTo(offset + 10, offset + 10); 
ctx.lineTo(offset, offset + 10); 
ctx.lineTo(offset, offset); 
ctx.stroke(); 

回答

0

好,這裏是像素完美矩形內行程:http://jsfiddle.net/kLZfc/9/

var ctx = document.querySelector('canvas').getContext('2d'); 
var offset; 
ctx.strokeStyle = "black" 
ctx.lineJoin = "miter"; 




var cSq = function(x, y, width, height, stroke){ 
    x = x + stroke/2; 
    y = y + stroke/2; 
    ctx.lineWidth = stroke; 
    ctx.lineCap = "square"; 
    ctx.beginPath(); 
    ctx.strokeStyle = 'red'; 
    ctx.lineTo(x, y); 
    if(stroke === 1){ 
     ctx.lineTo(x + width, y); 
    }else{ 
     ctx.lineTo(x + width - stroke, y); 
    } 
    ctx.moveTo(x + width - stroke, y); 
    ctx.lineTo(x + width - stroke, y + height - stroke); 
    ctx.lineTo(x, y + height - stroke); 
    ctx.moveTo(x, y + height - stroke * 2); 
    ctx.lineTo(x, y); 
    ctx.globalAlpha = 0.5 
    ctx.stroke() 
    ctx.globalAlpha = 0.7 
    ctx.fillRect(x + stroke/2, y + stroke/2, width - stroke*2, height - stroke*2) 
} 
cSq(10, 11, 10, 15, 1); cSq(15, 22, 25, 44, 5);