popup(3)

来源:互联网 发布:淘宝手机店铺装修教程 编辑:程序博客网 时间:2024/06/05 16:35

在body中我只放了一个canvas元素定义宽高;

<canvas id="cloth" width="500" height="500"></canvas>

定义canvas的背景吧:

canvas {            background: yellow;        }

然后就是编写脚本了;

<script>//获取元素创建画布    var ctx = document.getElementById("cloth").getContext("2d");    //定义矩形类,默认四个属性    var Rect = function (x1, y1, x2, y2) {        this.x1 = x1;        this.x2 = x2;        this.y1 = y1;        this.y2 = y2;    }    //定义画矩形的方法    Rect.prototype.drawRect = function (x) {        x.fillStyle = "#" + getRandomN(255, 0).toString(16) + getRandomN(255, 0).toString(16) + getRandomN(255, 0).toString(16);        x.fillRect(this.x1, this.y1, this.x2, this.y2)    };    //定义清除画布的方法    var clearRec = function () {        ctx.clearRect(getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0))    }    //定义获取随机数的方法    function getRandomN(max, min) {        return Math.floor(Math.random() * (max - min) + min)    }    //定义创建一个矩形的函数    function createoneR() {        var rec = new Rect(getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0));        rec.drawRect(ctx);    }    //定时器,    setInterval(function () {        createoneR();        createoneR();        clearRec();        createoneR();        clearRec();    }, 200)</script>

生成的效果是
这里写图片描述
源码是:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <style>        canvas {            background: yellow;        }    </style></head><body><canvas id="cloth" width="500" height="500"></canvas><script>    var ctx = document.getElementById("cloth").getContext("2d");    var Rect = function (x1, y1, x2, y2) {        this.x1 = x1;        this.x2 = x2;        this.y1 = y1;        this.y2 = y2;    }    Rect.prototype.drawRect = function (x) {        x.fillStyle = "#" + getRandomN(255, 0).toString(16) + getRandomN(255, 0).toString(16) + getRandomN(255, 0).toString(16);        x.fillRect(this.x1, this.y1, this.x2, this.y2)    };    var clearRec = function () {        ctx.clearRect(getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0))    }    function getRandomN(max, min) {        return Math.floor(Math.random() * (max - min) + min)    }    var rect1 = new Rect(10, 10, 100, 100);    function createoneR() {        var rec = new Rect(getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0), getRandomN(500, 0));        rec.drawRect(ctx);    }    setInterval(function () {        createoneR();        createoneR();        clearRec();        createoneR();        clearRec();    }, 200)</script></body></html>
原创粉丝点击