在HTML画布上清除和重绘正方形的过程

时间:2017-01-01 20:49:38

标签: javascript

我一直在研究一些HTML / Javascript代码,我想要发生的主要事情就是当你按下任意一个箭头键时,我画的方块会向那个方向移动。

我对我要做的事情的一般思路是,当我点击键时,它首先清除画布,然后根据函数用不同的x和y值重绘它。

我试过了,但发生的事情就是广场消失了,我不知道为什么。

我一直试图调试一段时间,如果有人有任何指示我会喜欢在这里!

<!DOCTYPE html>
   <html>
     <head>
    <title> HTML </title>
    <style>
        canvas {
            border: 1px solid #000000;
        }
    </style>
</head>
<body>
    <center>
        <canvas width = "620" height = "620" id = "myCanvas" ></canvas>
    </center>
    <script src = "script.js" > </script>
</body>
</html>

这是Javascript代码(很抱歉没有很好的格式化,仍然在StackOverflow中获取格式化代码)

document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) 
    moveLeft();
if(event.keyCode == 39 )
    moveRight();
if(event.keyCode == 38) 
    moveUp();
if(event.keyCode == 40)
    moveDown();
});

 function moveLeft() {
context.clearRect(0, 0, canvas.width, canvas.height);

//Edit X and Y Values

var newX, newY;
newX = squareX + 1;
newY = squareY;

context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);
}

function moveRight() {/* Needs to be Finished */}

function moveUp() {/* Needs to be Finished */}

function moveDown() {/* Needs to be Finished */}



var canvas;
var context;

var squareX, squareY;

var squareSizeX = 75;
var squareSizeY = 75;

function renderToCanvas() {
    var didRender = false;

try {
    canvas = document.getElementById("myCanvas");
    context = canvas.getContext("2d");
    /* INPUT DRAWING HERE */

    //Drawing Square

    squareX = canvas.width / 2;
    squareY = canvas.height / 2;

    context.rect(squareX, squareY, squareSizeX, squareSizeY);
    context.fillRect(squareX, squareY, squareSizeX, squareSizeY);
    context.stroke();

    /* END DRAWING HERE */

    didRender = true;
    console.log("Rendered Drawing: " + didRender);
}

catch(err) {
    console.log("Rendered Drawing: " + didRender);
    console.log(err.message);
    }
}


renderToCanvas();

1 个答案:

答案 0 :(得分:1)

moveLeft代替此

context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);

这样做

context.fillRect(newX, newY, squareSizeX, squareSizeY);

Check out the docs for Canvas Context

使用context.rect()时,您只能使用context.fill()context.beginPath()