[英]Centering a div on top of a canvas that is responsively sized to window.innerWidth and window.innerHeight
I am trying to add some text to the middle of my canvas background.我正在尝试在画布背景的中间添加一些文本。 I am having the hardest time figuring out how to add a div ON TOP OF IT, that will maintain position through resolution changes.我最难弄清楚如何在它的顶部添加一个 div,它将通过分辨率更改保持位置。
To start, here is how my canvas is being sized.首先,这是我的画布大小的方式。
var canvas = document.getElementById('first-canvas'); var ctx = canvas.getContext('2d'); initialize() function initialize() { window.addEventListener('resize', resizeCanvas, false); resizeCanvas(); } function redraw() { ctx.strokeStyle = 'black'; ctx.lineWidth = '5'; ctx.strokeRect(0, 0, window.innerWidth, window.innerHeight); } function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; redraw(); }
html, body { display: flex; flex-direction: row; width: 100%; height: 100%; margin: 0px; border: 0; /* No floating content on sides */ } body { overflow-x: hidden; } #btn-container { display: flex; justify-content: center; text-align: center; } #first-canvas { background-color: #393939; overflow: hidden; position: relative; } #scroll-btn { display: flex; justify-content: center; text-align: center; position: absolute; top: 0px; margin: 0; padding: 0; font-color: white; border: solid 2px white; width: 250px; height: 75px; }
<section class="canvas"> <canvas id="first-canvas" style="position:relative; left: 0px; top: 0px;"></canvas> <a href="#"> <div id="btn-container"> <div id="scroll-btn"> <h3>View My Page></h3> </div> </a> </div> <section>
Basically, I want to add a div right in the middle of the canvas so that i can add some welcoming text and maintain my scroll-btn.基本上,我想在画布中间添加一个 div,以便我可以添加一些欢迎文本并保持我的滚动 btn。
html,
body {
display: flex;
flex-direction: row;
width: 100%;
height: 100%;
margin: 0px;
border: 0;
/* No floating content on sides */
}
body {
overflow-x: hidden;
}
#btn-container {
display: flex;
justify-content: center;
text-align: center;
}
#first-canvas {
background-color: #393939;
overflow: hidden;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#scroll-btn {
display: flex;
justify-content: center;
text-align: center;
margin: 0;
padding: 0;
font-color: white;
border: solid 2px white;
width: 250px;
height: 75px;
}
.canvas {
width: 100%;
height: 100%;
position: relative;
}
a {
display: block;
position: absolute;
z-index: 1;
top: calc(100% - 37.5px);
left: calc(100% - 125px);
}
h3 {
margin: auto;
}
I found an awesome answer!我找到了一个很棒的答案!
div {
background:green;
position:fixed;
color:#fff;
width:50px;
height:50px;
top:50%;
left:50%;
-ms-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.