首页 > 解决方案 > 画布地图坐标

问题描述

我想在 800x800px 的画布上为 [-5, 5] 中的 x 绘制 exp(x)。我设法在水平轴上将 [-5, 5] 映射到 [0, 800],但我正在努力将 [exp(-5), exp(5)] 映射到垂直轴上的 [800, 0] .
关于如何做到这一点的任何想法?提前致谢。

标签: javascripthtmlmath

解决方案


这是一个详细的例子。i并且j是画布坐标白色x并且y是函数坐标。

基本上,映射 from ytoj类似于映射 from to 的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>


推荐阅读