其他分享
首页 > 其他分享> > canvas绘制左右来回移动,触碰边缘返回的小黑方块~

canvas绘制左右来回移动,触碰边缘返回的小黑方块~

作者:互联网

完整代码如下:

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
		canvas{
			background:#f2f2f2;
		}
	</style>
  <script></script>
 </head>
 <body>
  <canvas width="500" height="400" id="canvas"></canvas>
	<script>
		var ctx=canvas.getContext('2d');
		var x=0;
		var y=0;
		var s=10;
		setInterval(function(){
					ctx.clearRect(0,0,500,400);
					ctx.fillRect(x,y,50,40);
					x+=s;
					if(x>=450){s=-10}
					else if(x<=0){s=10}
		},100);
	</script>
 </body>
</html>

标签:触碰,10,canvas,f2f2f2,ctx,var,方块
来源: https://blog.csdn.net/qq_24618061/article/details/121567386