0

我需要用不重叠的路径制作一个矩形(因为我希望一些边缘是另一种颜色,例如或另一种带点线的线型等等)(所以当我将 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();
4

1 回答 1

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);
于 2013-01-19T15:54:54.647 回答