在我的一个HTML5画布元素中,创建了一些元素,如矩形,圆形和图像。
我的要求是按键(向下,向上,向左,向右)只需要移动图像。
移动图像位置时清除所需的整个画布?
我的代码看起来像
var canvas;
var width;
var height;
var imgMonsterARun = new Image();
var jeep=new Image();
var mySprite = {
x: 200,
y: 200,
width: 50,
height: 50,
speed: 200,
color: '#000'
};
$(document).ready(function(){
canvas=$("#canvas")[0];
//nvas.fill
width=canvas.width;
height=canvas.height;
var ctxr = canvas.getContext("2d");
ctxr.fillStyle="white";
ctxr.fillRect(0,0,width,height);
ctxr.strokeStyle="black";
ctxr.strokeRect(0,0,width,height);
jeep.src = "images/me.jpg";
});
$(document).keydown(function(e){
var key=e.which;
var x=mySprite.x;
var y=mySprite.y;
alert(x);
if(key=="37"){
// left
}
if (key=="38"){
// up
}
if (key=="39"){
// up
}
if (key=="40"){
// down
}
});
我是新手。我想按下右侧的吉普车
提前致谢
答案 0 :(得分:0)
我强烈建议你阅读Seteve和Jeff Fulton写的这本精彩的书,它在线免费,它涵盖了画布编程的所有难点:
http://chimera.labs.oreilly.com/books/1234000001654/index.html
答案 1 :(得分:-1)
<强> HTML:强>
<canvas id="canvas"></canvas>
<强> JS:强>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'http://upload.wikimedia.org/wikipedia/en/3/35/Information_icon.svg';
canvas.width = 800;
canvas.height = 600;
var mySprite = {
x: 200,
y: 200,
width: 50,
height: 50,
speed: 200,
color: '#c00'
};
var keysDown = {};
window.addEventListener('keydown', function(e) {
keysDown[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
delete keysDown[e.keyCode];
});
function update(mod) {
if (37 in keysDown) {
mySprite.x -= mySprite.speed * mod;
}
if (38 in keysDown) {
mySprite.y -= mySprite.speed * mod;
}
if (39 in keysDown) {
mySprite.x += mySprite.speed * mod;
}
if (40 in keysDown) {
mySprite.y += mySprite.speed * mod;
}
}
function render() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = mySprite.color;
ctx.drawImage(img, mySprite.x, mySprite.y, mySprite.width, mySprite.height);
}
function run() {
update((Date.now() - time) / 1000);
render();
time = Date.now();
}
var time = Date.now();
setInterval(run, 10);