javascript - 如何根据给定的坐标绘制具有倾斜 Angular 和旋转 Angular 矩形?

标签 javascript math canvas

enter image description here 结果与框架不完全匹配... 如何通过给定的 4 个坐标在 Canvas 舞台上绘制一个矩形?

给定的坐标有一点倾斜 Angular ,我没能用倾斜 Angular 绘制它,不知道如何用4个坐标计算倾斜 Angular 这是我到目前为止所能得到的,我可以用旋转 Angular 来绘制它。我还错过了什么?您可以复制 html 代码并查看结果..

This告诉我们如何用三 Angular 形计算倾斜 Angular ,但如何在矩形中使用它..

我是高中生,数学不太好,请见谅..:(

谢谢..

var _width, _height;
var img = new Image();
var img2 = new Image(),
  img2Widht = 0,
  img2Height = 0;
img.src = "http://production.manboker.com/share/1.jpg";
var canvas = document.getElementById("canvas");
img.onload = function() {
  canvas.width = _width = this.width;
  canvas.height = _height = this.height;
  img2.src = "http://production.manboker.com/share/2.png";
  img2.onload = function() {
    step1();
  }
}

var coor = {
  leftTop: ["92", "569"],
  rightTop: ["672", "569"],
  leftBottom: ["109", "1437"],
  rightBottom: ["723", "1437"]
}

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

function step1() {
  ctx.clearRect(0, 0, _width, _height);
  ctx.globalCompositeOperation = 'source-over';
  ctx.drawImage(img, 0, 0);
  ctx.globalCompositeOperation = "multiply";
  ctx.save();
  ctx.translate(coor['leftTop'][0], coor['leftTop'][1]);
  ctx.rotate(radian(coor['leftTop'], coor['leftBottom']));
  img2Widht = distance(coor['leftTop'], coor['rightTop']);
  img2Height = distance(coor['leftTop'], coor['leftBottom']);
  ctx.drawImage(img2, 0, 0, img2Widht, img2Height);
  ctx.restore();
}

function distance(a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1];
  return Math.sqrt(x * x + y * y);
}

function radian(a, b) {
  return Math.atan2(a[0] - b[0], b[1] - a[1]);
}
* {
  padding: 0;
  margin: 0;
}
html,
body {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
<canvas id="canvas" style="position:absolute;"></canvas>

最佳答案

为了将平面图像正确地拟合到 3D 框架照片中,通常您不仅需要旋转和倾斜(或更一般的仿射变换),还需要投影变换。这种变换由四个点的图像唯一定义,只要这三个点不位于一条公共(public)线上。 Finding the Transform matrix from 4 projected points (with Javascript)关于数学 SE 和 Redraw image from 3d perspective to 2d这里是我描述如何做到这一点的答案。

关于javascript - 如何根据给定的坐标绘制具有倾斜 Angular 和旋转 Angular 矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41542068/

相关文章:

javascript - 在 JavaScript 中拉伸(stretch)图形以填充 Canvas 元素

javascript - python ajax请求出错

math - 32 位定点溢出

javascript - 无法在 Canvas 上绘图

python - 计算流中的标准偏差

actionscript-3 - 选择网格中中心单元格的公式/算法?

javascript - 我可以更改 Canvas 元素内的图像大小吗?

javascript - 如何在单击单选按钮之一时启用文本框

Javascript:如何检索 *string* 数字的小数位数?

javascript - 如何更改隐藏输入值然后使用 Django 表单发送它?