javascript - 在画布中旋转后的坐标问题
问题描述
我在画布上绘制一些矩形时遇到问题。
我的目标是画这个: https ://ibb.co/b6Hsc4w
0 1 2 3 4 5
0
1 X X X
2 X X
3 X X X
4
5
var canvas = document.querySelector('canvas');
canvas.width = 600;
canvas.height = 400;
var c = canvas.getContext('2d');
function Line(x, y, length, height, angle, color) {
this.x = x;
this.y = y;
this.length = length;
this.height = height;
this.angle = angle;
this.color = color;
this.draw = function () {
c.save();
c.translate(this.x, this.y);
if (this.angle > 0) {
c.rotate(this.angle * Math.PI / 180);
}
c.fillStyle = this.color;
c.fillRect(0, 0, this.length, this.height);
c.restore();
};
this.draw();
}
new Line(2, 1, 3, 1, 0, "black");
new Line(4, 1, 3, 1, 90, "green");
new Line(4, 3, 3, 1, 180, "red");
new Line(2, 3, 3, 1, 270, "blue");
但使用我收到的代码: https ://ibb.co/vwRX1sG
0 1 2 3 4 5
0 X
1 X X X
2 X X X
3 X
4
5
就像源点无法正常工作一样。
HTML 只包含一个画布元素,我没有使用任何特殊的库。
解决方案
问题是您在块的角落而不是中心旋转。下面我在第一个变换中添加了 0.5,然后在旋转后的第二个变换中减去它。你可以看到它在这里工作小提琴
function Line(x, y, length, height, angle, color) {
this.x = x;
this.y = y;
this.length = length;
this.height = height;
this.angle = angle;
this.color = color;
this.draw = function () {
c.save();
c.translate(this.x+0.5, this.y+0.5);
if (this.angle > 0) {
c.rotate(this.angle * Math.PI / 180);
}
c.translate(-0.5, -0.5);
c.fillStyle = this.color;
c.fillRect(0, 0, this.length, this.height);
c.restore();
};
this.draw();
}
new Line(2, 1, 3, 1, 0, "black");
new Line(4, 1, 3, 1, 90, "green");
new Line(4, 3, 3, 1, 180, "red");
new Line(2, 3, 3, 1, 270, "blue");
推荐阅读
- python - 找到点的 ConvexHull
- javascript - owlCarousel 在页面加载时显示两张幻灯片,但在调整大小时显示一张
- php - 如何在 CI4 中自动加载会话库一次并像 CI3 一样访问每个地方
- javascript - 当一个是数组映射时,使两个组件具有相同的高度
- node.js - 通过 NPM 将 FullCalendar 安装到 laravel 项目
- transparency - 如何将低于某个级别的颜色更改为透明度
- javascript - 如何计算估计时间精度
- python - 如何在 DRF 中只显示几个多对多关系?
- three.js - 将 Physijs 添加到我的threejs 时,它会阻止我的渲染
- r - 使用 pmap 和 c(...) 第 2 部分