会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132487个问题
Python 全系列/第一阶段:Python入门/编程基本概念 22188楼
JAVA 全系列/第五阶段:JavaWeb开发/Web实战案例 22189楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 22190楼
Python 全系列/第二阶段:Python 深入与提高/模块 22191楼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas多个小球随机运动.html</title>
    <style>
        canvas{
            border: 1px solid #000;
        }
    </style>
</head>
<body>
<canvas width="400px" height="300px">您的浏览器不支持canvas,请升级浏览器!</canvas>
</body>
<script>
    /*var modul = (function () {
        function getElement(eleName) {
            return document.querySelector(eleName);
        }
        return {
            getElement:getElement
        };
    })();
    var canvas = modul.getElement("canvas");
    var ctx = canvas.getContext("2d");
    console.log(canvas);*/
    var canvas = document.querySelector("canvas");
    var ctx = canvas.getContext("2d");

    function randomColor() {
        var r = parseInt(Math.random() * 256);
        var g = parseInt(Math.random() * 256);
        var b = parseInt(Math.random() * 256);
        var CircleColor = "rgb(" + r + "," + g + "," + b + ")";
        return CircleColor;
    }
    function Circle() {
        this.r = Math.floor(Math.random() * 20 + 11);
        this.x = Math.floor(Math.random() * (400 - this.r));
        this.y = Math.floor(Math.random() * (300 - this.r));
        this.speedX = Math.floor(Math.random() * 8);
        this.speedY = Math.floor(Math.random() * 6);
        this.color = randomColor();
    }
    Circle.prototype.circleSpeed = function () {
        this.x += this.speedX;
        if (this.x <= this.r){
            this.speedX = -this.speedX;
        }else if (this.x >= (400 - this.r)){
            this.speedX = -this.speedX;
        }
        this.y += this.speedY;
        if (this.y <= this.r){
            this.speedY = -this.speedY;
        }else if (this.y >= (300 - this.r)){
            this.speedY = -this.speedY;
        }
    };
    Circle.prototype.drawCircle = function () {
        ctx.beginPath();
        ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.closePath();
    };
    var arr = [];
    for (var i = 0; i < 4; i++){
        arr[i] = new Circle();
    }
    var timer = setInterval(function () {
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for (var i = 0; i < arr.length; i++){
            arr[i] = circleSpeed();
            arr[i] = drawCircle();
        }
    },18);
</script>
</html>

哪里有问题?

WEB前端全系列/第九阶段:HTML5新特性模块/(旧)H5新特性 22192楼
Python 全系列/第八阶段:轻量级Web开发利器-Flask框架/Flask高级 22193楼
Python 全系列/第五阶段:数据库编程/python操作mysql(旧) 22194楼
Python 全系列/第一阶段:Python入门/面向对象 22197楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637