利用循环语句随机创建矩形
1.html语句:
1 <script> 2 (function () { 3 var canvas = document.querySelector('#cavsElem'); 4 var ctx = canvas.getContext('2d'); 5 canvas.width = 600; 6 canvas.height = 600; 7 canvas.style.border = "1px solid #000"; 8 var canvasHide = document.createElement('canvas');//创建一个canvas; 9 canvasHide.width = canvas.width; 10 canvasHide.height = canvas.height; 11 var ctxHide = canvasHide.getContext('2d'); 12 for (var i = 0; i < 1000; i++) { 13 var r = new fun({ 14 x: Math.random() * 100, 15 y: Math.random() * 100, 16 w: Math.random() * 100, 17 h: Math.random() * 100, 18 rotation: Math.random() * 90, 19 opacity: Math.random() 20 }); 21 r.render(ctxHide); 22 } 23 ctx.drawImage(canvasHide, 0, 0); 24 }()); 25 </script>
2.js代码:
<script> function fun(option) { this._init(option); } fun.prototype = { _init: function (option) { this.x = option.x || 0; this.y = option.y || 0; this.h = option.h || 0; this.w = option.w || 0; this.rotation = option.rotation || 0; this.opacity = option.opacity == 0 ? 0 : option.opacity || 1; this.scaleX = option.scaleX || 1; this.scaleY = option.scaleY || 1; this.strokeStyle = option.strokeStyle || 'red'; this.fillStyle = option.fillStyle || 'blue'; }, render: function (ctx) { ctx.save(); ctx.beginPath(); ctx.translate(this.x, this.y); ctx.rotate(this.rotation * Math.PI / 180); ctx.globalAlpha = this.opacity; ctx.scale(this.scaleX, this.scaleY); ctx.rect(0, 0, this.w, this.h); ctx.fillStyle = this.fillStyle; ctx.fill(); ctx.strokeStyle = this.strokeStyle; ctx.stroke(); ctx.restore(); } } </script>
一辈子很短,努力的做好两件事就好;第一件事是热爱生活,好好的去爱身边的人;第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;