温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用canvas怎么实现一个流水灯效果

发布时间:2021-05-21 15:45:23 来源:亿速云 阅读:148 作者:Leah 栏目:开发技术

使用canvas怎么实现一个流水灯效果?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

具体内容如下

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>基于canvas超炫酷的流水灯效果</title>  
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        canvas{
            border: 1px solid red;
            width: 100%;
            height: 100%;
        }
    </style>
</head>  
<body  onselectstart="return false">  
        <!-- 添加canvas标签,并加上红色边框以便于在页面上查看 -->  
        <canvas id="myCanvas" >  
        您的浏览器不支持canvas标签。   
        </canvas>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
    var canvas = document.getElementById("myCanvas");  
    var ctx = canvas.getContext("2d");    
    var cx1 = canvas.offsetLeft;
    var cy1 = canvas.offsetTop;
    var cx2 = canvas.offsetLeft + canvas.offsetWidth;
    var cy2 = canvas.offsetTop + canvas.offsetHeight;
    var bbox = canvas.getBoundingClientRect();  
    $(function(){
        var direction = 'right',x = y = right_count = down_count = left_count = up_count = 0;
        ctx.beginPath(); //开始一个新的绘制路径
        ctx.moveTo(x, y); //定义直线的起点坐标为(0,0)
        setInterval(function(){
            ctx.strokeStyle = '#'+Math.floor(Math.random()*16777215).toString(16);
            switch(direction){
                case 'right':
                    if(x >= 300 - right_count){
                        direction = 'down';    
                        right_count++;
                    }else{
                        x++;
                    }
                    break;
                case 'down':
                    if(y >= 150 - down_count){
                        direction = 'left';
                        down_count++;
                    }else{
                        y++;
                    }
                    break;
                case 'left':
                    if(x <= left_count){
                        direction = 'up';
                        left_count++;
                    }else{
                        x--;
                    }
                    break;
                case 'up':
                    if(y <= up_count + 1){
                        direction = 'right';
                        up_count++;
                    }else{
                        y--;
                    }
                    break;
            }
            ctx.lineTo(x, y);
            ctx.lineCap = 'round';
            ctx.lineWidth = 1; //设置线段的宽度
            ctx.stroke(); //沿着坐标点顺序的路径绘制直线
        }, 1);
    }) 
</script>  
</body>  
</html>

关于使用canvas怎么实现一个流水灯效果问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI