clearRect left和top not clearing

时间:2018-05-05 01:39:44

标签: javascript

我想创建一个在画布中移动的简单对象。用键盘控制器。但clearRect没有按预期工作。并且如果可以给出示例和多个keydown检测,如按右箭头顶部将使x和y增加1

  

window.requestAnimationFrame

    "use strict";

const canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');

var width = 1366;
var height = 544;

canvas.width = width;
canvas.height = height;
canvas.style.backgroundColor = 'black';

var x = 0;
var y = 0;
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,15,15);

window.addEventListener('keydown', function(event){
    var o = event.keyCode;
    switch (o) {
        case 37:
            x -= 1;
            ctx.fillRect(x, y, 15, 15);
            ctx.clearRect(x-1, y, 1, 15);
            break;
        case 38:
            y -= 1;
            ctx.fillRect(x, y, 15, 15);
            ctx.clearRect(x, y-1, 15, 1);
            break;
        case 39:
            x += 1;
            ctx.fillRect(x, y, 15, 15);
            ctx.clearRect(x-1, y, 1, 15);
            break;
        case 40:
            y += 1;
            ctx.fillRect(x, y, 15, 15);
            ctx.clearRect(x, y-1, 15, 1);
            break;
        default:
    }
});

document.body.appendChild(canvas);

THX

1 个答案:

答案 0 :(得分:0)

我添加了一行来清除整个画布然后再填充。试试这个方法。

const canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');

var width = 1366;
var height = 544;

canvas.width = width;
canvas.height = height;
canvas.style.backgroundColor = 'black';

var x = 0;
var y = 0;
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,15,15);

window.addEventListener('keydown', function(event){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    var o = event.keyCode;
    switch (o) {
        case 37:
            x -= 1;
            ctx.fillRect(x, y, 15, 15);
            break;
        case 38:
            y -= 1;
            ctx.fillRect(x, y, 15, 15);
            break;
        case 39:
            x += 1;
            ctx.fillRect(x, y, 15, 15);

            break;
        case 40:
            y += 1;
            ctx.fillRect(x, y, 15, 15);

            break;
        default:
    }
});

document.body.appendChild(canvas);