javascript 画布上的 HTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16586734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html over the Canvas?
提问by Phil
Can someone clear up some some confusion on my part.
有人可以澄清我的一些困惑。
Is it possible to have html over the top of a canvas? I keep reading that you can't have GUI elements such as Jquery with Canvas, but then I read you can have HTML over the canvas, why can you have one but not the other?
是否可以在画布顶部放置 html?我一直读到你不能有 GUI 元素,比如 Jquery 和 Canvas,但后来我读到你可以在画布上有 HTML,为什么你可以有一个而不是另一个?
What I ideally want eventually is a good GUI over the top of my canvas, so just need to know what's possible and what isn't.
我最终想要的是在我的画布顶部有一个很好的 GUI,所以只需要知道什么是可能的,什么是不可能的。
回答by Woody
Sure - you can put the HTML "on top" of the canvas by using absolute positioning.
当然 - 您可以使用绝对定位将 HTML 放在画布的“顶部”。
http://jsfiddle.net/stevendwood/5sSWj/
http://jsfiddle.net/stevendwood/5sSWj/
You cannot have HTML "in" the canvas. But supposing that the canvas and the HTML use the same coordinates then you can use top and left to position elements in the canvas using the same offsets as you draw with.
画布中不能有 HTML。但是假设画布和 HTML 使用相同的坐标,那么您可以使用 top 和 left 使用与绘制时相同的偏移量来定位画布中的元素。
#picture {
position: relative;
}
.blob, .blob1, .blob2 {
position: absolute;
width: 30px;
height: 30px;
border-radius: 20px;
background-color: green;
border: 2px solid #ccc;
}
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d');
context.beginPath();
context.moveTo(100, 150);
context.lineTo(350, 50);
context.stroke();
And the HTML...
和 HTML...
<div id="picture">
<canvas id="canvas" width="500" height="500">
</canvas>
<div class="blob1"></div>
<div class="blob2"></div>
</div>
In this fetching example you can connect two positioned divs with a line drawn on a canvas element that is underneath them.
在这个获取示例中,您可以使用在它们下方的画布元素上绘制的线连接两个定位的 div。
回答by Strille
The canvas element is no different than any other dom element, so you can place any dom element on top of a canvas element.
canvas 元素与任何其他 dom 元素没有什么不同,因此您可以将任何 dom 元素放在 canvas 元素之上。
jQuery is just a means to manipulatethe DOM, so of course you can use jQuery for the GUI. What you cannot do is use jQuery to manipulate the contents of the canvas itself (the pixel data), maybe that's what the confusion is about.
jQuery 只是一种操作DOM的手段,所以当然你可以将 jQuery 用于 GUI。你不能做的是使用 jQuery 来操作画布本身的内容(像素数据),也许这就是混淆所在。
回答by Nitesh
You can place an element above canvas with position:absolute;
for any HTML element that you need to place above the canvas. Hope this helps.
position:absolute;
对于需要放置在画布上方的任何 HTML 元素,您可以将元素放置在画布上方。希望这可以帮助。