【问题标题】:HTML5 Canvas y-height not correctHTML5 Canvas y 高度不正确
【发布时间】:2015-05-24 12:17:42
【问题描述】:

所以我只是想制作一个简单的动画 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);
    }
}

【问题讨论】:

    标签: javascript css html animation canvas


    【解决方案1】:

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

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

    然后删除这些:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-09
      • 2012-06-13
      • 2017-06-12
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多