画布地图坐标

时间:2019-02-12 10:03:41

标签: javascript html math

我想在800x800px的画布上为[-5,5]中的x绘制exp(x)。我设法在水平轴上将[-5,5]映射到[0,800],但是我在垂直轴上却将[exp(-5),exp(5)]映射到[800,0] 。
关于如何做到这一点的任何想法?预先感谢。

2 个答案:

答案 0 :(得分:1)

这里是执行此操作的方法的详细示例。 ij是画布坐标,白色xy是函数坐标。

基本上,从yj的映射类似于从xi的映射的逆过程。但是您必须从高度中减去结果,因为在画布上绘制时y坐标是相反的。

var c = document.querySelector('canvas');
var ctx = c.getContext('2d');
ctx.beginPath();

const width = 400;
const height = 150;

// The bounds
const minx = -5;
const maxx = 5;
const miny = Math.exp(-5);
const maxy = Math.exp(5);

ctx.moveTo(0, height);

for (let i = 0; i < width; i += width / 100) {
  // Get x from canvas coordinates
  const x = i / width * (maxx - minx) + minx;
  const y = Math.exp(x);
  // Transform y to canvas coordinates
  const j = height - (y - miny) / (maxy - miny) * height;
  // Draw in canvas coordinates
  ctx.lineTo(i, j);
}

ctx.stroke();
canvas {
  border: 1px solid black;
}
<canvas width=400 height=150></canvas>

答案 1 :(得分:0)

我认为该线程可以为您提供帮助:

Convert position coordinates to canvas coordinates

希望这就是您想要的。