Reputation: 81
I have a HTML5 canvas with height = 640. I expect the text with following style to be in the middle
top = 320px;
position = 'absolute'
however this goes below the canvas, and
top = 140px;
looks like it is centered.
Screenshots: 140_640 | 320_640
What am I getting wrong? Should I try to use and do it in JS rather than CSS?
canvas.getContext("2d");
Upvotes: 0
Views: 75
Reputation: 2571
You should place the text inside the canvas and use the canvas textAlign
and fillText
to set the content and the position
var canvas = document.getElementById("gl-canvas");
var ctx = canvas.getContext("2d");
ctx.textAlign = "center";
ctx.fillText(canvas.textContent,430, 320);
<canvas id="gl-canvas" width="860" height="640">
<div>
<span>Game Over! You...</span>
</div></canvas>
Upvotes: 1
Reputation: 5708
If you know the height of <span id="game-over">
then just do this:
// Add this to your CSS for #game-over
// example span id="game-over" height of 200px;
#game-over
{
position:absolute;
top:50%;
margin-top:-100px;
}
If you don't know the <span id="game-over">
height then I would do this:
// Add this to your CSS for #game-over
#game-over
{
position:absolute;
top:50%;
}
To check the height of the element and set the margin in javascript
:
var gameOver = document.getElementById("game-over");
// get height
var heightOfText = gameOver.style.height;
// get half of height
heightOfText = parseInt(heightOfText)/2;
// set negative margin to center it
gameOver.style.marginTop = "-" + heightOfText.toString() + "px"
Upvotes: 1