简体   繁体   English

画90度角线的算法

[英]Algorithm for drawing lines with 90-degree angles

To get straight to the point, what I hope to achieve is to be able to create a connecting line between two elements with this shape:开门见山,我希望实现的是能够在具有这种形状的两个元素之间创建一条连接线:

演示图片

DBDIAGRAM.IO DBDIAGRAM.IO

When the elements move, the line resets but always maintains a 90 degree angle, instead of being a straight or diagonal line between [x,y] to [x,y].当元素移动时,该线会重置但始终保持 90 度角,而不是 [x,y] 到 [x,y] 之间的直线或对角线。

Is there some kind of algorithm for this?这有某种算法吗? Maybe a grid with some kind of A* implementation?也许是具有某种 A* 实现的网格?

I don't know how to make rounded corners easy, but the easiest example will be this:我不知道如何轻松制作圆角,但最简单的示例是:

 const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') // define the points const p1 = { x: 30, y: 50 } const p2 = { x: 150, y: 130 } ctx.strokeStyle = 'red' // draw the points ctx.beginPath() ctx.arc(p1.x, p1.y, 5, 0, Math.PI * 2) ctx.stroke() ctx.beginPath() ctx.arc(p2.x, p2.y, 5, 0, Math.PI * 2) ctx.stroke() // get distance between const horizontalDistance = p2.x - p1.x ctx.strokeStyle = 'black' // draw left part ctx.beginPath() ctx.moveTo(p1.x, p1.y) ctx.lineTo(p1.x + horizontalDistance / 2, p1.y) ctx.stroke() // draw vertical part ctx.beginPath() ctx.moveTo(p1.x + horizontalDistance / 2, p1.y) ctx.lineTo(p1.x + horizontalDistance / 2, p2.y) ctx.stroke() // draw right part ctx.beginPath() ctx.moveTo(p1.x + horizontalDistance / 2, p2.y) ctx.lineTo(p2.x, p2.y) ctx.stroke()
 canvas { border: 1px solid black; }
 <canvas></canvas>

Real-time version:实时版本:

 const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') const p1 = { x: canvas.width / 2, y: canvas.height / 2 } const p2 = { x: 150, y: 130 } canvas.addEventListener('mousemove', e => { const mousePos = getMousePos(canvas, e) p2.x = mousePos.x p2.y = mousePos.y }) loop() function loop() { draw() requestAnimationFrame(loop) } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.strokeStyle = 'red' ctx.beginPath() ctx.arc(p1.x, p1.y, 5, 0, Math.PI * 2) ctx.stroke() ctx.beginPath() ctx.arc(p2.x, p2.y, 5, 0, Math.PI * 2) ctx.stroke() const horizontalDistance = p2.x - p1.x ctx.strokeStyle = 'black' ctx.beginPath() ctx.moveTo(p1.x, p1.y) ctx.lineTo(p1.x + horizontalDistance / 2, p1.y) ctx.stroke() ctx.beginPath() ctx.moveTo(p1.x + horizontalDistance / 2, p1.y) ctx.lineTo(p1.x + horizontalDistance / 2, p2.y) ctx.stroke() ctx.beginPath() ctx.moveTo(p1.x + horizontalDistance / 2, p2.y) ctx.lineTo(p2.x, p2.y) ctx.stroke() } function getMousePos(canvas, evt) { const rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; }
 canvas { border: 1px solid black; }
 <canvas></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM