我一直在弄乱 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/