结果与帧完美匹配...... 如何通过给定4个坐标在画布舞台上绘制矩形?
给定的坐标有一个小的倾斜角度,我无法用倾斜角度绘制它,不知道如何用4坐标计算倾斜角度 这是我到目前为止所得到的,我可以用旋转角度绘制它。我还错过了什么?你可以复制HTML代码并查看结果..
This讲述了如何用三角形计算倾斜角度,但如何在矩形中使用它。
我是高中生,我的数学不太好,请原谅我.. :(
谢谢..
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>
&#13;
答案 0 :(得分:0)
为了将平面图像正确地拟合到3d中的帧的照片中,通常不仅需要旋转和倾斜(或更一般的仿射变换),而是需要投影变换。这种变换由四个点的图像唯一地定义,只要这三个点中没有三个位于共同线上。数学SE上的Finding the Transform matrix from 4 projected points (with Javascript)和SO上的Redraw image from 3d perspective to 2d是答案,我在此描述如何做到这一点。