假設我有一行表格:x1, y1, x2, y2和一個給定的thickness.
我正在尋找一種方法將該線轉換為圍繞其原點旋轉的矩形,這樣如果您將它們都繪制在畫布上,它們將完全重疊。
我已經開發了我在下面面臨的問題的完整再現:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const thickness = 7;
const lineX1 = 25, lineY1 = 50;
const lineX2 = 100, lineY2 = 100;
function rotateCanvas(x, y, a) {
ctx.translate(x, y);
ctx.rotate(a);
ctx.translate(-x, -y);
}
function drawRectangle(rX, rY, rW, rH, rA, color) {
ctx.beginPath();
ctx.fillStyle = "#dd3333";
rotateCanvas(rX rW / 2, rY rH / 2, rA);
ctx.rect(rX, rY, rW, rH);
rotateCanvas(rX rW / 2, rY rH / 2, -rA);
ctx.fill();
}
function drawLine(x1, y1, x2, y2) {
ctx.lineWidth = thickness;
ctx.strokeStyle = "#33dd33";
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function calcRectFromLine(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
const mag = Math.sqrt(dx * dx dy * dy);
const angle = Math.atan2(dy, dx);
return { x: x1, y: y1, w: mag, h: thickness, a: angle };
}
drawLine(lineX1, lineY1, lineX2, lineY2);
const r = calcRectFromLine(lineX1, lineY1, lineX2, lineY2);
drawRectangle(r.x, r.y, r.w, r.h, r.a);
<canvas></canvas>
如果您運行代碼,您會看到紅色矩形不在綠線的頂部。我想以某種方式解決這個問題。
我相信唯一需要修復的功能是calcRectFromLine. 理想情況下,這將回傳一個矩形,當傳遞給 時drawRectangle,將導致綠線不再可見,因為它將被紅色矩形完全覆寫。
我也相信我需要使用某種sin和cos來抵消紅色矩形,但我不確定實作這一點的確切數學。
uj5u.com熱心網友回復:
您使用旋轉線的坐標不正確地計算矩形左和上。更正:
return { x: (x1 x2)/2 - mag/2, y: (y1 y2)/2 - thickness/2,
w: mag, h: thickness, a: angle };`
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const thickness = 7;
const lineX1 = 25, lineY1 = 50;
const lineX2 = 100, lineY2 = 100;
function rotateCanvas(x, y, a) {
ctx.translate(x, y);
ctx.rotate(a);
ctx.translate(-x, -y);
}
function drawRectangle(rX, rY, rW, rH, rA, color) {
ctx.beginPath();
ctx.fillStyle = "#dd3333";
rotateCanvas(rX rW / 2, rY rH / 2, rA);
ctx.rect(rX, rY, rW, rH);
rotateCanvas(rX rW / 2, rY rH / 2, -rA);
ctx.fill();
}
function drawLine(x1, y1, x2, y2) {
ctx.lineWidth = thickness;
ctx.strokeStyle = "#33dd33";
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function calcRectFromLine(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
const mag = Math.sqrt(dx * dx dy * dy);
const angle = Math.atan2(dy, dx);
return { x: (x1 x2)/2 - mag/2, y: (y1 y2)/2 - thickness/2, w: mag, h: thickness, a: angle };
}
drawLine(lineX1, lineY1, lineX2, lineY2);
const r = calcRectFromLine(lineX1, lineY1, lineX2, lineY2);
drawRectangle(r.x, r.y, r.w, r.h, r.a);
<canvas><\canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464869.html
標籤:javascript 数学 回转 html5-画布 三角学
上一篇:如何求解具有兩個變數的指數方程?
下一篇:計算更多的19位除法
