zoukankan      html  css  js  c++  java
  • 随机方块

    1:tools.js

    var Tools = {
    getRandom: function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    }

    2:

    // 生成10个方块,随机生成颜色

    // 获取容器
    var container = document.getElementById('container');


    // 数组,存储创建的方块对象
    var array = [];
    for (var i = 0; i < 10; i++) {
    var r = Tools.getRandom(0, 255);
    var g = Tools.getRandom(0, 255);
    var b = Tools.getRandom(0, 255);

    var box = new Box(container, {
    backgroundColor: 'rgb('+ r +','+ g +','+ b +')'
    });


    // 把创建好的方块对象,添加到数组中
    array.push(box);
    }


    // 设置随机位置,开启定时器
    setInterval(randomBox, 500);

    // 页面加载完成,先设置随机位置
    randomBox();

    function randomBox() {
    // 随机生成方块的坐标
    for (var i = 0; i < array.length; i++) {
    var box = array[i];
    box.random();
    }
    }

    3:

    function Box(parent, options) {
    options = options || {};
    // 设置对象的属性
    this.backgroundColor = options.backgroundColor || 'red';
    this.width = options.width || 20;
    this.height = options.height || 20;
    this.x = options.x || 0;
    this.y = options.y || 0;

    // 创建对应的div
    this.div = document.createElement('div');
    parent.appendChild(this.div);
    this.parent = parent;

    // 设置div的样式
    this.init();
    }

    // 初始化div (方块)的样式
    Box.prototype.init = function () {
    var div = this.div;
    div.style.backgroundColor = this.backgroundColor;
    div.style.width = this.width + 'px';
    div.style.height = this.height + 'px';
    div.style.left = this.x + 'px';
    div.style.top = this.y + 'px';
    // 脱离文档流
    div.style.position = 'absolute'
    }

    // 随机生成方块的位置
    Box.prototype.random = function () {
    // 父容器的宽度/方块的宽度 总共能放多少个方块
    var x = Tools.getRandom(0, this.parent.offsetWidth / this.width - 1) * this.width;
    var y = Tools.getRandom(0, this.parent.offsetHeight / this.height - 1) * this.height;

    this.div.style.left = x + 'px';
    this.div.style.top = y + 'px';
    }

  • 相关阅读:
    SpringBoot启动里的细节问题
    SpringBoot运行过程从SpringApplication开始解读
    SpringBoot应用启动流程
    SpringBoot上传相关配置
    planUML时序图
    JAVA设计模式--单例模式
    中国云运营商横向对比——IaaS服务对标
    ansible api2.0 多进程执行不同的playbook
    自动化运维平台搭建
    django-将数据库数据转换成JSON格式(ORM和SQL两种情况)
  • 原文地址:https://www.cnblogs.com/pxxdbk/p/12502743.html
Copyright © 2011-2022 走看看