canvas 线锯齿

ctx.beginPath();
ctx.lineWidth = 20;
ctx.moveTo(15, 15);
ctx.lineTo(100, 30);
ctx.stroke();

ctx.imageSmoothingEnabled = true;
ctx.webkitImageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
x,y 移动0.5 均不能解决锯齿问题

// 移动端可以解决锯齿的问题,pc端使用不明显, 效果比较好 https://developpaper.com/question/how-can-the-canvas-diagonal-be-anti-aliasing/
// 锯齿不清晰问题
// 处理锯齿
function aliasing(canvas, context) {
const width = canvas.width;
const height = canvas.height;
if (window.devicePixelRatio) {
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
canvas.height = height * window.devicePixelRatio;
canvas.width = width * window.devicePixelRatio;
context.scale(window.devicePixelRatio, window.devicePixelRatio);
}
}

方法二:
https://riptutorial.com/html5-canvas/example/18144/line-without-blurryness
这种方式比lineTo绘制慢很多, 并且还是有锯齿

// Usage:
bresenhamLine(50,50,250,250);

// x,y line start
// xx,yy line end
// the pixel at line start and line end are drawn
function bresenhamLine(ctx,x, y, xx, yy){
    var oldFill = ctx.fillStyle;  // save old fill style
    ctx.fillStyle = ctx.strokeStyle; // move stroke style to fill
    xx = Math.floor(xx);
    yy = Math.floor(yy);
    x = Math.floor(x);
    y = Math.floor(y);
    // BRENSENHAM 
    var dx =  Math.abs(xx-x); 
    var sx = x < xx ? 1 : -1;
    var dy = -Math.abs(yy-y);
    var sy = y<yy ? 1 : -1; 
    var err = dx+dy;
    var errC; // error value
    var end = false;
    var x1 = x;
    var y1 = y;

    while(!end){
       ctx.fillRect(x1, y1, 1, 1); // draw each pixel as a rect
        if (x1 === xx && y1 === yy) {
            end = true;
        }else{
            errC = 2*err;
            if (errC >= dy) { 
                err += dy; 
                x1 += sx; 
            }
            if (errC <= dx) { 
                err += dx; 
                y1 += sy; 
            } 
        }
    }
    ctx.fillStyle = oldFill; // restore old fill style
}

bresenhamLine(ctx, 15, 15, 100, 30)

posted @ 2022-08-15 16:33  Running00  阅读(652)  评论(0编辑  收藏  举报