我不擅长几何,所以对我来说只看公式并理解它是如何工作的会更容易。我需要一个 Javascript 公式,以便我可以在旋转画布后找到点。
<canvas width="910" height="300"></canvas>
canvas{
width:100%;
height:300px;
outline:1px solid red;
}
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
let w = canvas.clientWidth;
let h = canvas.clientHeight;
let line_width = 1;
let degrees = 0;
let rad = 0;
ctx.lineWidth = line_width;
ctx.setLineDash([5,20]);
ctx.strokeStyle = 'red';
let x_1 = w/2;
let y_1 = h/2;
let x_2 = w;
let y_2 = h;
ctx.beginPath();
ctx.moveTo(x_1, y_1);
ctx.lineTo(x_2, y_2);
ctx.stroke();
ctx.translate(w/2,h/2);
degrees += 45;
rad = degrees * (Math.PI/180);
ctx.rotate(rad);
ctx.translate(-w/2,-h/2);
ctx.beginPath();
ctx.moveTo(x_1, y_1);
// Find the coordinates of the point and draw a line.
//x_2 = ?
//y_2 = ?
决定了。问题已结束。这对我有帮助:在给定角度查找矩形上的点
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
let w = canvas.clientWidth;
let h = canvas.clientHeight;
canvas.width = w;
canvas.height = h;
let line_width = 1;
let degrees = 45;
let rad = 0;
ctx.lineWidth = 1;
ctx.setLineDash([5,20]);
ctx.strokeStyle = 'red';
let x_1 = w/2 - line_width/2;
let y_1 = h/2 - line_width/2;
let x_2 = 910;
let y_2 = 150;
ctx.beginPath();
ctx.moveTo(x_1, y_1);
let rect = { width:w, height: h };
let coords = get_end_point(rect, degrees);
x_2 = coords.x;
y_2 = coords.y;
ctx.lineTo(x_2, y_2);
ctx.stroke();
function get_end_point(rect, deg){
let twoPI = Math.PI * 2;
let theta = -1 * (deg * Math.PI / 180);
while(theta < -Math.PI){
theta += twoPI;
}
while(theta > Math.PI){
theta -= twoPI;
}
let rectAtan = Math.atan2(rect.height, rect.width);
let tanTheta = Math.tan(theta);
let region;
if((theta > -rectAtan) && (theta <= rectAtan)){
region = 1;
}
else if((theta > rectAtan) && (theta <= (Math.PI - rectAtan))){
region = 2;
}
else if((theta > (Math.PI - rectAtan)) || (theta <= -(Math.PI - rectAtan))){
region = 3;
}
else{
region = 4;
}
let edgePoint = {x: rect.width/2, y: rect.height/2};
let xFactor = 1;
let yFactor = 1;
switch(region){
case 1: yFactor = -1; break;
case 2: yFactor = -1; break;
case 3: xFactor = -1; break;
case 4: xFactor = -1; break;
}
if((region === 1) || (region === 3)){
edgePoint.x += xFactor * (rect.width / 2.);
edgePoint.y += yFactor * (rect.width / 2.) * tanTheta;
}
else{
edgePoint.x += xFactor * (rect.height / (2. * tanTheta));
edgePoint.y += yFactor * (rect.height / 2.);
}
return edgePoint;
}