HTML5 Canvas y-height不正确

时间:2015-03-20 23:46:59

标签: javascript css html5 animation canvas

所以我只是想用一个动画块制作一个简单的动画HMTL画布,它使用WASD在画布上移动。我最初注意到在画布上画了一个大小为5,5的矩形,看起来像一个大小为5,10的矩形。在测试我的重绘功能并在控制台中打印画布中元素的x和y位置时,我注意到我的矩形可以在X方向上从1-300开始,但在Y方向上只有1-150。即使画布的样式为300,300,也会发生这种情况。任何人都可以弄明白我是否做过傻事?

    <!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="script.js" defer></script>
</head>
<body>
    <div class="text-holder holder" id="instruction-holder">
        <p class="text" id="instruction">Use WASD to navigate around the viewer</p>
    </div>
    <div class="holder" id="canvas-holder">
        <canvas id="canvas"></canvas>
    </div>
</body>
</html>

和css

    #canvas {
    width: 300px;
    height:300px;
    margin-left: auto;
    margin-right: auto;
    display: block;
    border-style: solid;
    border-color: grey;
    border-radius: 1px;
}

.holder {
    display: block;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

和js

var UP = "87", DOWN = "83", LEFT = "65", RIGHT = "68", X = 10, Y = 5, XSIZE = 10, YSIZE = 5;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var xPos, yPos;

window.addEventListener("load",init);
document.addEventListener('keydown',move);

function init() {
    xPos = 1;
    yPos = 1;
    ctx.fillStyle = "black";
    ctx.fillRect(xPos,yPos,XSIZE,YSIZE);
}

function clear() {
    ctx.clearRect(0,0,300,300);
}

function reDraw(delX, delY) {
    console.log(yPos+delY + " " + (xPos+delX));
    if (xPos+delX > 0 && xPos+delX < 300 && 
        yPos+delY > 0 && yPos+delY < 150) {
        clear();
        ctx.fillStyle = "black";
        xPos = xPos+delX;
        yPos = yPos+delY;
        ctx.fillRect(xPos,yPos,XSIZE,YSIZE);
    }
}

function move(ev) {
    var delX, delY;
    var key = ev.keyCode;
    if (key == UP) {
        delX = 0;
        delY = -Y;
    } else if (key == DOWN) {
        delX = 0;
        delY = Y;
    } else if (key == LEFT) {
        delX = -X;
        delY = 0;       
    } else if (key == RIGHT) {
        delX = X;
        delY = 0;
    }

    if (delX != undefined && delY != undefined) {
        reDraw(delX, delY);
    }
}

1 个答案:

答案 0 :(得分:0)

您必须明确设置画布的大小,否则它将使用默认大小300x150(CSS仅缩放元素,而不是位图 - 300x150的位图被拉伸以适合您在CSS屏幕上看到的规则,但是位图在内部将保持相同的大小):

<canvas id="canvas" width=300 height=300></canvas>

然后删除这些:

#canvas {
  /* width: 300px; */
  /* height:300px; */
  ...