画布尺寸不一致

时间:2018-01-01 11:07:38

标签: javascript html css

我有一个高度= 640的HTML5画布。我希望以下样式的文字位于中间

top = 320px; 
position = 'absolute'

然而,这是在画布下方,

top = 140px;

看起来像是居中。

截图: 140_640 | 320_640

我错了什么?我应该尝试使用JS而不是CSS吗?

canvas.getContext("2d"); 

2 个答案:

答案 0 :(得分:1)

如果您知道<span id="game-over">的高度,那么就这样做:

// 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;
}

如果您不知道<span id="game-over">高度,那么我会这样做:

// Add this to your CSS for #game-over
#game-over
{
    position:absolute;
    top:50%;
}

检查元素的高度并在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"

答案 1 :(得分:1)

您应该将文本放在画布中并使用画布textAlignfillText来设置内容和位置

&#13;
&#13;
var canvas = document.getElementById("gl-canvas");
var ctx = canvas.getContext("2d"); 
ctx.textAlign = "center";     
ctx.fillText(canvas.textContent,430, 320);
&#13;
<canvas id="gl-canvas" width="860" height="640">
<div>
<span>Game Over! You...</span>
</div></canvas>
&#13;
&#13;
&#13;