HTML5中的画布:删除先前的矩形

Joh*_*nny 3 javascript html5 canvas

我一直在搞弄html5中的canvas元素,这是经过一些试验后得到的结果

function canvasMove(e) {

    var canvas = document.getElementById('game');

    if(canvas.getContext) {
        var draw = canvas.getContext('2d');

        draw.fillStyle = 'rgba(0,0,0,0.5)';
        draw.fillRect('10', '10', '100', '100');    

        var code;

        if (!e) var e = window.event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);

        if(character == '&') { draw.translate(0, -10); }
        if(character == '(') { draw.translate(0, 10); }
        if(character == '%') { draw.translate(-10, 0); }
        if(character == "'") { draw.translate(10, 0); }
    }
}
Run Code Online (Sandbox Code Playgroud)

它的作用是每当您按箭头键时都会移动矩形[箭头键显示为&,(,%和',不确定每个人是否都一样,但这只是一个实验]。无论如何,我可以移动矩形周围,但是会留下某种残留物,因为它不会删除它以前的形式,所以我得到的是使用非常厚的笔刷进行的非常基本的etch-n'-sketch。

我想要做的是能够删除矩形的先前形式,以便仅保留新的翻译版本。

最重要的是,我想知道如何通过同时按下向左和向上来使其水平移动。我知道我的代码可能不是很通用,但是任何帮助我们都非常感谢。

谢谢 :)

Sim*_*ris 6

我为你做了一个例子。您的HTML必须调用我的init()函数。我用了:

<body onLoad="init()">
Run Code Online (Sandbox Code Playgroud)

让我知道您是否有任何问题

var canvas;
var draw;

var WIDTH;
var HEIGHT;

var x = 10;
var y = 10;

// in my html I have <body onLoad="init()">
function init() {
    canvas = document.getElementById('game');
    HEIGHT = canvas.height;
    WIDTH = canvas.width;
    draw = canvas.getContext('2d');

    // every 30 milliseconds we redraw EVERYTHING.
    setInterval(redraw, 30);

    // canvas.keydown = canvasMove;

    document.onkeydown = canvasMove; 
}

//wipes the canvas context
function clear(c) {
    c.clearRect(0, 0, WIDTH, HEIGHT);
}

//clears the canvas and draws the rectangle at the appropriate location
function redraw() {
    clear(draw);
    draw.fillStyle = 'rgba(0,0,0,0.5)';
    draw.fillRect(x, y, '100', '100');   
}

function canvasMove(e) {
  if(e.keyCode == '38') { y -= 1; }
  if(e.keyCode == '40') { y += 1; }
  if(e.keyCode == '37') { x -= 1; }
  if(e.keyCode == "39") { x += 1; }
}
Run Code Online (Sandbox Code Playgroud)