【问题标题】:Draw an image with 2 points on a canvas在画布上绘制带有 2 个点的图像
【发布时间】:2015-11-19 12:35:17
【问题描述】:

我必须点 (x1, x2, y1, y2)。如何在画布上绘制一个图像(它就像一个宽度为 10 和高度为 100 的矩形),起点为 x1,y1 和旋转度由这两点之间的线的斜率决定?

就像我想用图像重叠这条线:

ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();

我试过这样:

slope = (y2 - y1) / (x2 - x1)
ctx.save();
ctx.rotate(-Math.atan(slope));
ctx.drawImage(image, x1, y1);
ctx.restore();

但没有成功。

谢谢。

【问题讨论】:

  • 当你说没有成功时,究竟是什么问题?
  • 图像和线条不重叠。连旋转的角度都不一样。
  • 您能在jsbin 中重现您的问题吗?
  • 超过 2 行的图像搞砸了。

标签: javascript html canvas html5-canvas draw


【解决方案1】:

ctx.rotate 将围绕画布原点旋转上下文。

为了围绕形状的拐角旋转,您需要将上下文翻译到该点。

var slope = (pt.y1 - pt.y2) / (pt.x1 - pt.x2);
ctx.save();
ctx.translate(pt.x1, pt.y1);
ctx.rotate(Math.atan(slope));
// we've already moved to here, so we can draw at 0, 0
ctx.drawImage(image, 0, 0);
ctx.restore();

这仅适用于正斜率。如果斜率为负,也可以通过反转旋转来解释负斜率。

var slopeIsNegative = slope < 0;
var offsetAngle = slopeIsNegative ? Math.PI : 0;
ctx.rotate(Math.atan(slope) + offsetAngle);

【讨论】:

  • 好的,但是负斜率的线条有问题。 jsfiddle.net/36vfdx27/79
  • [-0.5,0] 之间的斜率存在问题。就像我从未添加过 PI
  • 看看你是否能找到需要偏移的角度来纠正它,然后扩展该 if 语句以覆盖边缘情况。
  • @DanPrince: 使用Math.atan2 来解释各个象限中的角度,而Math.atan 没有。
猜你喜欢
  • 2014-09-03
  • 2016-07-08
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
相关资源
最近更新 更多