gpt4 book ai didi

javascript - 将 div(带有边框和填充)悬停在 Canvas 元素的中心?

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:48 25 4
gpt4 key购买 nike

我希望 div 正好位于水平中心。我试过这个:

var div = document.createElement();
div.textContent = 'Hello World!';
div.className = 'button';
div.style.position = 'absolute';
div.style.left = (0.5 * canvas.width) + canvas.offsetLeft + 'px';

button定义如下:

.button{
color : black;
padding : 10px;
border : solid black 3px;
border-radius : 10px;
overflow : none;
}

显然,定义从左边开始的像素恰好是 Canvas 的一半存在问题:文本的宽度可变。如果我能找到文本的宽度,我可以将它除以 2,然后从我当前分配给 left 属性的宽度中减去它。

我试过用 absolute 位置制作一个 div,它悬停在 Canvas 正上方并将所有文本对齐到 centerdiv 中,但这也不起作用。

请尝试在不使用任何库的情况下使用纯 JavaScript 给出您的答案。

最佳答案

使用ctx.measureText,正确设置ctx.font后:http://jsfiddle.net/SFR82/2/ .

我还建议在 CSS 中正确使用 border,例如 3px solid black

var ctx = canvas.getContext("2d");

ctx.font = "12pt Times New Roman"; // same as <div> font; this is default for me

var textSize = ctx.measureText(text);

...

div.style.left = 0.5 * canvas.offsetWidth // half canvas width
+ canvas.offsetLeft // plus left position
- (textSize.width / 2) // minus half of text width
- 10 // minus padding
- 3 // minus border size
+ 'px';

关于javascript - 将 div(带有边框和填充)悬停在 Canvas 元素的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8137417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com