如何通过在背景画布中绘制线条来连接两个 HTML 元素?

2022-01-17 00:00:00 jquery html html5-canvas

可能更多的是一道数学题,但这里是……

Probably more of a math question, but here it goes...

我想要做的是通过背景画布上的动画线连接两个 HTML 元素

What I want to do is two HTML elements to be connected by an animated line on a background canvas

这是我想做的简化版本的小提琴.

Here is a fiddle with a simplified version of what I want to do.

http://jsfiddle.net/loupax/zUqXn/

线条确实存在,但它们在画布之外,如果您使用元素检查器,您可以看到画布中绘制的线条的坐标.有人可以帮我解决我做错了什么并且线条不合适吗?

The lines are actually there, but they are outside of the canvas, and if you use your element inspector you can see the coordinates of the drawn lines in the canvas. Could someone help me on what I'm doing wrong and the lines get drawn out of place?

这证明了线条是画出来的,但不合适.(用固定尺寸替换流体舞台和画布尺寸)

This is the proof that the lines are drawn but out of place. (replaced fluid stage and canvas size with fixed dimensions)

http://jsfiddle.net/loupax/zUqXn/8/

编辑看起来我正在尝试做的事情对于流畅的布局是不可能的.经过很多麻烦后,我发现 Canvas 元素是它自己的平面,并且没有安全的方法可以将锚坐标与没有固定大小的画布坐标匹配

EDIT Looks like what I'm trying to do is not possible for a fluid layout. After a lot of trouble I found out that the Canvas element is it's own plane and there is no safe way to match anchor coordinates with canvas coordinates with no fixed sizes

推荐答案

我找到了错位的原因.

似乎CSS的canvas宽度和高度与canvas元素的实际宽度和高度完全不同.因此,如果您希望 HTML 元素的坐标与 Canvas 元素上的线条坐标相匹配,则需要在包含它的 div 上设置固定宽度,并且直接在元素上设置相同且固定的宽度和高度

It seems like that CSS width and height of canvas is completely different than the actual width and height of the canvas element. So if you wish to make the coordinates of the HTML elements match the coordinates of the lines on the Canvas element, you need to set fixed width on the div that contains it and the same and fixed width and height, directly on the element

这是固定示例,您可以看看:

Here is the fixed example so you can have a look:

http://jsfiddle.net/loupax/zUqXn/29/

相关文章