簡體   English   中英

帆布/精確線條畫

[英]Canvas / precise line drawing

我現在正在玩javascript和canvas。

我想畫一個沒有模糊線條的1像素邊框。 我讀過有關0.5 px的翻譯。

var shift = 0.5;
if (x1 === x2) {
  var shiftX = shift;
  var shiftY = 0;
} else {
  var shiftX = 0;
  var shiftY = shift;
}

怎么了 ? 的jsfiddle

為什么右下角會丟失一個像素?

這個有效!!

ctx.line = function (x1, y1, x2, y2) {
    var shift = 0.5;

    if (x1 === x2) {
        var shiftX = x1 < 2 ? shift : -shift;
        var shiftY = 0;
    } else if (y1 === y2) {
        var shiftX = 0;
        var shiftY = y1 < 2 ? shift : -shift;
    } else {
        var shiftX = 0;
        var shiftY = 0;
    }

    ctx.translate(shiftX, shiftY);
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    ctx.translate(-shiftX, -shiftY);
};

您嘗試的問題是太靠近邊緣的像素可能會從畫布“移開”。 該方法確保如果該點在邊緣的2個像素內,則移位發生在距邊緣的AWAY方向上。

屏幕像素的中心是它的(+ 0.5,+ 0.5)context2d坐標。

事實是你不必為x OR y翻譯0.5,但對於兩者 ,無論是垂直線還是水平線。

您的整個代碼與此相同:

ctx.sline(0    , 0.5,      399,   0.5);
ctx.sline(399.5 ,0,        399.5, 399);
ctx.sline(0     ,399.5,    399,   399.5);
ctx.sline(0.5   ,399,      0.5,   0);
// With 'sline' a straight line function that just use provided coordinates.

很容易看出點不會相互連接。 這里涉及8點,而不是4點。
永遠不會達到右下角的最高點(399.5,399.5),而其他角落至少有2個點。

一勞永逸地解決問題的一種簡單方法是在創建上下文時將畫布轉換為(0.5,0.5),然后使用舍入坐標。
顯然 - 它應該始終完成 - 使用轉換時保存/恢復上下文。

http://jsfiddle.net/gamealchemist/xaxK4/6/

ctx.translate(0.5, 0.5);
ctx.lineWidth = 1;
ctx.strokeStyle = "#AAAAAA";

ctx.line = function (x1, y1, x2, y2) {
    x1 = 0 | x1 ;
    y1 = 0 | y1 ;
    x2 = 0 | x2 ;
    y2 = 0 | y2 ;
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
};

ctx.line(1, 1, 399, 1);
ctx.line(399, 1, 399, 399);
ctx.line(399, 399, 1, 399);
ctx.line(1, 399, 1, 1);

並且不要使用css寬度/高度,或者可以在代碼中設置它以確保你永遠不會有canvas.width!= canvas.style.width或canvas.height!= canvas.style.height,除非你知道你是什么當然,做不同的價值觀。 但是,如果您不打算使用分辨率,支持hiDpi設備或以較低分辨率渲染,請使用css大小調整退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM