我希望 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 正上方并将所有文本对齐到 center
在 div
中,但这也不起作用。
请尝试在不使用任何库的情况下使用纯 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/