先看看下面的效果图,想想使用canvas是怎样实现的?

如下图:

canvas实现类似弹窗广告效果

 

这个就不详细描述了,看代码就会了。

 

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas</title>
    <style type="text/css">
        #canvas {
            border:1px solid red;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script type="text/javascript">
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = "red";
    ctx.fillRect(0,0,80,50);

    var speedX = 1,
        speedY = 2,
        i1 = 0,
        i2 = 0;
        w = 80,
        h = 50,
        dirX = true,
        dirY = true;
    function run() {
        
        if(dirX) {
            i1++;
        }else {
            i1--;
        }
        if(dirY) {
            i2++;
        }else {
            i2--;
        }
        //清除画布
        ctx.clearRect(0,0,400,400);

        //判断边界
        if(i1*speedX > (canvas.width - w)) {
            dirX = false;
        }else if(i1*speedX < 0){
            dirX = true;
        }

        if(i2*speedY > (canvas.height - h)) {
            dirY = false;
        }else if(i2*speedY < 0) {
            dirY = true;
        }
        //绘制矩形
        ctx.fillRect(i1*speedX,i2*speedY,w,h);
        window.requestAnimationFrame(run);
    }
    window.requestAnimationFrame(run);
    </script>
</body>
</html>

 

相关文章:

  • 2022-01-08
  • 2021-05-10
  • 2021-11-01
  • 2022-12-23
  • 2021-06-17
  • 2021-10-13
  • 2022-01-09
  • 2021-07-11
猜你喜欢
  • 2021-10-19
  • 2021-12-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-29
  • 2022-12-23
相关资源
相似解决方案