前端开发canvas-小球跳动

前端开发常用浏览器的区别
前端融资和开发贷区别
游戏前端开发与后端开发的区别

html 代码

<!DOCTYPE html>
    <head>
        <meta charset=”UTF-8″ />
        <title>小球跳动</title>
        <style type=”text/css”>
            canvas {
                border: 3px solid orange;
                margin: 0 auto;
                display: block;
            }
        </style>
    </head>
    <body>
        <canvas id=”myCanvas” width=”600″ height=”600″></canvas>
    </body>
    <script type=”text/javascript”>
        //获取绘制环境
        var canvas = document.getElementById(‘myCanvas’)
        var canvasObj = canvas.getContext(‘2d’)
        //随机函数
        function randomFun(x, y) {
            return Math.floor(Math.random() * (y – x + 1) + x)
        }
        function Ball() {
            this.r = randomFun(10, 30)
            this.color =
                ‘rgb(‘ +
                randomFun(0, 255) +
                ‘,’ +
                randomFun(0, 255) +
                ‘,’ +
                randomFun(0, 255) +
                ‘)’
            this.x = randomFun(this.r, canvas.width – this.r)
            this.y = randomFun(this.r, canvas.height – this.r)
            this.speedX = randomFun(3, 6) * (randomFun(0, 1) ? 1 : -1)
            this.speedY = randomFun(3, 6) * (randomFun(0, 1) ? 1 : -1)
        }
        Ball.prototype.move = function() {
            this.x += this.speedX
            this.y += this.speedY
            if (this.x <= this.r) {
                this.x = this.r
                this.speedX *= -1
            }
            if (this.x >= canvas.width – this.r) {
                this.x = canvas.width – this.r
                this.speedX *= -1
            }
            if (this.y <= this.r) {
                this.y = this.r
                this.speedY *= -1
            }
            if (this.y >= canvas.height – this.r) {
                this.y = canvas.height – this.r
                this.speedY *= -1
            }
        }
        Ball.prototype.draw = function() {
            canvasObj.beginPath()
            canvasObj.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
            canvasObj.fillStyle = this.color
            canvasObj.fill()
        }
        var balls = []
        for (var i = 0; i < 10; i++) {
            var ball = new Ball()
            ball.draw()
            balls.push(ball)
        }
        setInterval(function() {
            canvasObj.clearRect(0, 0, canvas.width, canvas.height)
            for (var i = 0; i < balls.length; i++) {
                balls[i].move()
                balls[i].draw()
            }
        }, 100)
    </script>
</html>
开发和前端的区别\\\’
as开发与前端开发的区别
web开发前端和后端的区别
» 本文来自:前端开发者 » 《前端开发canvas-小球跳动》
» 本文链接地址:https://www.rokub.com/7024.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!