javascript 在 div 上覆盖画布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16502319/
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
Overlay a canvas over a div
提问by Bernice
I have a div and I want to overlay a canvas exactly on top of it with the same width, height, padding and margins. Although I am using position: absolute like most questions here recommend and z-index the canvas is still showing underneath the div. This is the code I have until now.
我有一个 div,我想用相同的宽度、高度、填充和边距在它上面完全覆盖一个画布。虽然我使用 position: absolute 就像这里推荐的大多数问题一样,并且 z-index 画布仍然显示在 div 下方。这是我到现在为止的代码。
<div id ="editor-section">
<div class="editable" id="editor"></div>
</div>
// the canvas is created / removed dynamically on connection / disconection
hub.client.broadcastSomeoneConnected = function (connectionId, someoneConnected)
{
if (someoneConnected) {
var canvas = document.createElement("canvas");
canvas.id = connectionId;
canvas.className = 'canvases';
canvas.style.border = '2px solid red';
canvas.style.zIndex = zindex;
zindex++;
var parentDiv = document.getElementById("editor-section");
parentDiv.appendChild(canvas);
} else { // someone disconnected
var canvas = document.getElementById(connectionId);
canvas.parentNode.removeChild(canvas);
}
}
// css for all canvases
.canvases {
width:60%;
height:700px;
border:1px solid;
position:absolute;
padding: 5%;
margin-left:20px;
pointer-events: none;
}
// css for editor div
#editor {
padding: 5%;
margin-left:20px;
border: 2px solid black;
overflow-y:scroll;
height: "700px";
width: "100%";
background-color: white;
margin-bottom:30px;
}
PS: zindex is initialized globally because I need multiple canvases layered on top of each other and the editor eventually depending on the number of people connected
PS:zindex 是全局初始化的,因为我需要多个画布层叠在一起,编辑器最终取决于连接的人数
What am I doing wrong here? Thanks
我在这里做错了什么?谢谢
回答by nice ass
Almost there. Move width and height on the container, make it relative, and the editor and canvas absolutely positioned at 0,0 with 100% width/height. The zIndex
of your editor must be lower than the zIndex
of your canvas. fiddle
快好了。移动容器上的宽度和高度,使其相对,编辑器和画布绝对定位在 0,0 处,宽度/高度为 100%。该zIndex
编辑器必须比下zIndex
你的画布。小提琴