设置一个变量来表示移动方向:如下代码中设置一个
var xDirection = 1;
如果值为1则代表右移,x坐标自增;
如果值为-1则代表左移。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
body {
text-align: center;
}
canvas {
background: #f0f0f0;
}
</style>
</head>
<body>
<h3>绘制路径——上下移动的飞机</h3>
<canvas id="c8" width="600" height="400"></canvas>
<script>
var ctx = c8.getContext('2d');
var p3 = new Image();
p3.src = "img/p3.png";
p3.onload = function(){
//碰撞弹回算法
var x = 0;
var xDirection = 1; //1(右)或-1(左)
var y = 0;
var yDirection = 1; //1(下)或-1(上)
setInterval(function(){
ctx.clearRect(0,0, 600, 400);
x += 5*xDirection;
y += 5*yDirection;
ctx.drawImage(p3, x, y);
if(x>=(600-200)){ //已到最右侧
xDirection = -1; //-1代表左移
}else if(x<=0){ //已到最左侧
xDirection = 1; //1代表右移
}
//////////////////////////////////
if(y>=(400-100)){ //已到最下侧
yDirection = -1; //-1代表上移
}else if(y<=0){ //已到最上侧
yDirection = 1; //1代表下移
}
},20)
}
</script>
</body>
</html>