当alpha为<时,如何创建具有填充和笔划和笔划的路径的矩形不会重叠。 1?

时间:2013-01-19 14:29:42

标签: canvas rectangles

我需要制作一个带路径的矩形(因为我想要一些边缘是另一种颜色,例如或其他线型点缀等等),这些颜色不重叠(所以当我将alpha设置为0.5时,某些边缘会用帆布2d不要因为重叠而变暗。

我尝试使用lineCap,但它在alpha中重叠...

检查我做了什么,但不是很好。 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();

1 个答案:

答案 0 :(得分: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);