关于javascript 中drawImage(),图像位置,如何封装一个函数来生成多个图片,不同位置;

var img=new Image();
img.src="..."
function draw(obj,x,y){
ctx.drawImage(obj,x,y)
}
比如是这样的,
但是我要键盘方向键能控制这图片,
document.addEventListener("keydown",function(){
如何控制这图移动
不要说弄个中间变量,var x=...;var y=...;再弄个速度var spd=...;
不要这样的!!;

},false)

倒不如说怎么给img坐标

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>_</title>
<script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
img.onload = function(){
draw(this, 10, 10);
};

function draw(img, x, y){
if(img){
this.img = img;
this.x = x;
this.y = y;
this.width = img.width;
this.height = img.height;
}else{
if(!this.img) return;

ctx.clearRect(this.x, this.y, this.x + this.width, this.y + this.height);
img = this.img;
x += this.x;
y += this.y;
this.x = x;
this.y = y;
}
ctx.drawImage(img, x, y);
}

var size = 5;
$(document.body).keydown(function(event){
switch(event.keyCode){
case 37: draw(null, -size, 0); break;
case 38: draw(null, 0, -size); break;
case 39: draw(null, size, 0); break;
case 40: draw(null, 0, size); break;
}
});
});
</script>
<body>
<canvas id="canvas" width="1000" height="500"></canvas>
</body>
</html>

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-02-21
将要变化的当成参数传递追问

看下补充的

相似回答