javascript - HTML5 中的 Canvas : Removing Previous Rectangle

标签 javascript html 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); }
    }
}

它所做的是在您按下箭头键时移动矩形 [箭头键显示为 &、(、% 和 ',不确定这是否对每个人都一样,但这只是一个实验]。无论如何,我可以四处移动矩形,但它会留下某种残留物,因为它不会删除它以前的形式,所以我得到的是使用非常厚的刷子的非常基本的 eclipse 刻-n'-草图。

我想做的是能够删除以前的矩形形式,只留下新的翻译版本。

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

谢谢:)

最佳答案

我给你举了个例子。您的 HTML 必须调用我的 init() 函数。我用过:

<body onLoad="init()">

如果有任何问题,请告诉我

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; }
}

关于javascript - HTML5 中的 Canvas : Removing Previous Rectangle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3416724/

相关文章:

javascript - 通过 Ajax 发送 HTML 表单并使用 PHP 处理

Javascript加载Image到Offscreen Canvas,进行webp转换

javascript - 当图像位于同一域时,Canvas 元素未呈现为 PNG(安全错误)

html - Bootstrap 页脚在调整为移动设备大小时左右间隙

javascript - 我是网页设计新手 - 这个系统能用吗?

java - JApplet中使用paintComponent绘制多条连接线

javascript - 异步函数返回空数组,然后返回所需的数据 - 导致应用程序崩溃

javascript - 无法将我的商店文件导入 App.js 错误 : 'store' should be listed in the project's dependencies

javascript - WKWebView javascript 方法 click() 不执行任何操作

javascript - AngularJS ng-click 带参数