javascript - 画布地图坐标
问题描述
我想在 800x800px 的画布上为 [-5, 5] 中的 x 绘制 exp(x)。我设法在水平轴上将 [-5, 5] 映射到 [0, 800],但我正在努力将 [exp(-5), exp(5)] 映射到垂直轴上的 [800, 0] .
关于如何做到这一点的任何想法?提前致谢。
解决方案
这是一个详细的例子。i
并且j
是画布坐标白色x
并且y
是函数坐标。
基本上,映射 from y
toj
类似于映射 from to 的x
逆i
。但是你必须从高度中减去结果,因为在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>
推荐阅读
- java - Spring JPA - findAll() 与示例/探针包括相关/加入实体
- bash - 这个 '${image##*/}' 大括号扩展有什么作用?
- python - Pycharm 与 cmd 终端有不同的输出
- css - calc 函数在容器中留下额外的空间,尽管孩子加起来 100% 减去排水沟
- elixir - 在 ecto 迁移中读取 html 文件
- python - 使用列表指定要使用的子词典
- git - Git pull 失败(403),没有提示输入密码
- sql - 老问题 - 但未解决:没有结果 SELECT * FROM table WHERE my_datetime_field BETWEEN start AND end
- intellij-idea - Intellij IDE 未运行单元测试
- ibm-cloud-private - IBM Cloud Private:如何提醒日志中的关键字