如何在 javascript 中使用画布缩放方法实现坐标重映射

问题描述 投票:0回答:0

我有一个简单的 HTML 画布和一个在上面画东西的 JavaScript。问题是,我实现了一个将

xOy
正交坐标系转换为屏幕坐标的重映射函数,因为我想做一些与 2D 欧几里德几何相关的事情:
所以,(0, 0) 不在左上角,而是在中间:

//canvasPos is a custom class(Vector2) with 2 fields, x and y. This parameters stores the
//pixel coordinates in xOy coordinates.
function convertCoordinates(canvasPos, width, height){
    return new Vector2(canvasPos.x + width / 2, Math.abs(canvasPos.y-height/2));
}

例如调用函数:

let test = convertCoordinates(new Vector2(0, 0), 200, 200);
console.log("(" + test.x + ", " + test.y + ")"); //outputs "(100, 100)"
let test = convertCoordinates(new Vector2(-100, 100), 200, 200);
console.log("(" + test.x + ", " + test.y + ")"); //outputs "(0, 0)"
let test = convertCoordinates(new Vector2(100, 100), 200, 200);
console.log("(" + test.x + ", " + test.y + ")"); //outputs "(200, 0)"

我还创建了一个 drawLine 函数:

function drawLine(ctx, from, to) {    
    let width = ctx.canvas.clientWidth;
    let height = ctx.canvas.clientHeight;
    let c1 = convertCoordinates(from, width, height);
    let c2 = convertCoordinates(to, width, height);
    ctx.beginPath();
    ctx.moveTo(c1.x, c1.y);
    ctx.lineTo(c2.x, c2.y);
    ctx.stroke();
}

现在我可以用我们在中学学到的坐标系画线了(我需要这个,因为它是某种与基础几何相关的教程)

现在,问题是我画的所有东西的分辨率都很低(文本、线条、省略号等)。我在网上搜索了很多关于这个主题的 Stack OverFlow 线程,但是大多数解决方案包括放大画布上下文,然后使用“ctx.scale();”缩小它。 其他方法包括创建一个缓冲位图,然后逐个像素地绘制它,但是我尝试在画布上锐化绘图的每个解决方案似乎都破坏了我的 convertCoordinates 函数,当我使用 ctx.scale() 或 ctx.translate 时,转换变得一团糟().

javascript html5-canvas vector-graphics coordinate-systems
© www.soinside.com 2019 - 2024. All rights reserved.