canvas画布:图像上下左右碰撞边缘弹回

版权声明:谁没个菜的时候! https://blog.csdn.net/qq_32584661/article/details/82257582
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>

        canvas{
            background:#9AA4FF;
        }

    </style>
</head>
<body>
<h3>canvas画布:图像上下左右碰撞边缘弹回</h3>

<canvas id="HuaBu">
    您的浏览器不支持canvas画布
</canvas>


<script src="js/jquery-1.11.1.js"></script>
<script>

    var w=600;
    var h=400;

    HuaBu.width=w;     //画布的宽
    HuaBu.height=h;    //画布的宽

    //创建画布
    var ctx=HuaBu.getContext("2d");

    var peo=new Image();
    peo.src="imgs/peo.png";

    peo.onload=function () {

        //为canvas元素绑定事件监听:让图像画在鼠标移动位置

        HuaBu.onclick=function (e) {

            //碰撞弹回算法(边缘弹回算法)
            var x=0;
            var xDrection=1;         //横向的移动方向,1或-1
            var y=0;
            var yDrection=1;         //竖向的移动方向,1或-1

            var peoWidth=peo.width;
            var peoHeight=peo.height;

           setInterval(function () {

               ctx.clearRect(0,0,w,h);   //清除画布

               x+=5*xDrection;
               y+=5*yDrection;

               ctx.drawImage(peo,x,y);    //画图像

               //横向的移动方向,1或-1
               if(x>=(w-peoWidth)){
                   xDrection=-1;     //-1:左移
               }else if(x<=0){
                   xDrection=1;     //1:右移
               };

               //竖向的移动方向,1或-1
               if(y>=(h-peoHeight)){
                   yDrection=-1;     //-1:左移
               }else if(y<=0){
                   yDrection=1;     //1:右移
               };


           },40);
            

        };
        
    }

</script>


</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_32584661/article/details/82257582