ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[面向对象的案例]在canvas画布内实现小球的随机移动

2020-03-27 23:00:34  阅读:275  来源: 互联网

标签:function rand canvas width 画布 面向对象 game speedY


图片描述

//css部分,给画布设置边框
<style>
    canvas {
        border:1px solid orange;
    }
</style>
//html 添加画布
<canvas id="game" width="500" height="500"></canvas>

准备工作
先确定所需要的属性
小球的起始xy坐标、R半径、颜色、速度speedXY。

//创建球构造函数
 function ball() {
        this.r = this.rand(20);
        this.x = this.r;
        this.y = this.r;
        this.speedX = this.rand(10);
        this.speedY = this.rand(10);
        this.width = 0;
        this.height = 0;
        this.canvas = {};
        this.color = 'rgb('+this.rand(255)+','+this.rand(255)+','+this.rand(255)+')';
        this.init();
    }
//2.向原型链添加方法
ball.prototype = {
        init:function () {
            var game = document.getElementById('game');
            this.canvas = game.getContext('2d');
            this.width=game.width;
            this.height=game.height;
        },
        rand:function (num) {
            return Math.floor(Math.random() * num+1);
        },
        play:function () {
            this.x += this.speedX;
            this.y += this.speedY;
            if (this.x>this.width-this.r) {
                this.speedX = -this.speedX;
            }
            if (this.x<this.r) {
                this.speedX = Math.abs(this.speedX);
            }
            if (this.y>this.width-this.r) {
                this.speedY = -this.speedY;
            }
            if (this.y<this.r) {
                this.speedY = Math.abs(this.speedY);
            }
            this.canvas.beginPath();
            this.canvas.fillStyle = this.color;
            this.canvas.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
            this.canvas.fill();
        }
    };
    //3.创建100个小球
    var arr = [];
    for (var i=0;i<100;i++) {
        arr[i] = new ball();
    }
    //4.使用定时器,每个30ms刷新屏幕
    setInterval(function () {
        arr[0].canvas.clearRect(0,0,500,500);
        for (var i=0;i<arr.length;i++) {
            arr[i].play();
        }
    },30)

标签:function,rand,canvas,width,画布,面向对象,game,speedY
来源: https://www.cnblogs.com/jlfw/p/12584940.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有