Javascript画布不重绘? [英] Javascript canvas not redrawing?

查看:177
本文介绍了Javascript画布不重绘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款游戏(基于画布),但我遇到了一个问题。显然,当我按下一个键,而不是画布更新对象的x和y时,它只是什么都不做。变量本身正在更新,但屏幕上的对象不是。这是代码:

I'm working on a game (canvas-based), and I've run into a problem. Apparently, when I press a key, instead of the canvas updating the x and y of the object, it's just doing nothing. The variable itsself is updating, but the object on screen is not. Here's the code:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);

var bluex = 560;
var bluey = 380;

var orangex = 20;
var orangey = 380;

ctx.fillStyle = "black";
ctx.fillRect(0, 0, 640, 480);

ctx.fillStyle = "orange";
ctx.fillRect(orangex, orangey, 64, 64);

ctx.fillStyle = "blue";
ctx.fillRect(bluex, bluey, 64, 64);

function keyDownHandler(event) {
    var keyPressed = String.fromCharCode(event.keyCode);

    if (keyPressed == "W") {
        orangey = orangey - 5;
        bluey = bluey - 5;
    } else if (keyPressed == "D") {
        orangex = orangex + 5;
        bluex = bluex - 5;
    } else if (keyPressed == "S") {
        orangey = orangey + 5;
        bluey = bluey + 5;
    } else if (keyPressed == "A") {
        orangex = orangex - 5;
        bluex = bluex + 5;
    }
    alert(bluex + " " + bluey);
}

document.onkeydown = keyDownHandler;

有谁知道如何解决这个问题?很抱歉,如果这是一个令人难以置信的基本代码问题。

Does anyone know how to fix this? Sorry if this is an incredibly basic code problem.

推荐答案

将您的功能更改为以下内容:

Change your function to the following:

function keyDownHandler(event) {
    var ctx = canvas.getContext("2d");
    var keyPressed = String.fromCharCode(event.keyCode);

    if (keyPressed == "W") {
        orangey = orangey - 5;
        bluey = bluey - 5;
    } else if (keyPressed == "D") {
        orangex = orangex + 5;
        bluex = bluex - 5;
    } else if (keyPressed == "S") {
        orangey = orangey + 5;
        bluey = bluey + 5;
    } else if (keyPressed == "A") {
        orangex = orangex - 5;
        bluex = bluex + 5;
    }
    ctx.fillStyle = "orange";
    ctx.fillRect(orangex, orangey, 64, 64);

    ctx.fillStyle = "blue";
    ctx.fillRect(bluex, bluey, 64, 64);
}

调用函数时没有调用你的ctx.fillStyle,但是变量得到了更新

Your ctx.fillStyle didn't got called when the function was called, but the variables got updated

这篇关于Javascript画布不重绘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆