canvas练手

本文主要探讨了如何利用HTML5的canvas元素进行前端图形绘制,通过JavaScript实现动态交互效果,加强了对canvas基本操作的理解和应用。
摘要由CSDN通过智能技术生成

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #circle {
            /* width: 500px;
            height: 500px; */
            display: block;
            margin: 0 auto;
            box-sizing: border-box;
            border: 2px solid #ccc;
        }
    </style>
</head>

<body>
    <canvas id="circle" width="500px" height="500px"></canvas>
    <script>
        /**@type {HTMLCanvasElement}*/
        var canvas = document.querySelector('#circle');
        var ctx = canvas.getContext('2d');

        var w = 500,
            h = 500;

        function Ball() {
            this.x = Math.random() * 440 + 60;
            this.y = Math.random() * 440 + 60;
            this.r = Math.random() * 60;
            this.c = 'rgb(' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ',' +
                parseInt(Math.random() * 255) + ')';
            this.xspeed = Math.random() * 10 + (-5);
            this.yspeed = Math.random() * 8 + (-4);
        };

        //创造小球
        Ball.prototype.creat = function() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
            ctx.fillStyle = this.c;
            ctx.fill();
        };

        //小球移动
        Ball.prototype.move = function() {
            ctx.beginPath();
            //判断小球是否离开画布可视区,若离开则改变运动方向
            if (this.xspeed + this.x <= this.r || this.xspeed + this.x >= 500 - this.r) {
                this.xspeed = -this.xspeed;
            }
            if (this.yspeed + this.y <= this.r || this.yspeed + this.y >= 500 - this.r) {
                this.yspeed = -this.yspeed;
            }
            this.x = this.x + this.xspeed;
            this.y = this.y + this.yspeed;
        };
        //创建一个小球数组
        var ballArr = [];
        for (var i = 0; i < 100; i++) {
            var ball = new Ball();
            ballArr.push(ball);
            console.log(ball)
            ball.creat();
        };
        setInterval(function() {
            ctx.clearRect(0, 0, w, h);
            for (var j = 0; j < ballArr.length; j++) {
                var ball = ballArr[j];
                ball.move();
                ball.creat();
            }
        }, 30);
        // console.log(ballArr);
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

染星_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值