canvas_demo01.js

1    var canvasDemo01 = {}; 
2     
3    (function(app) { 
4      'use strict'; 
5     
6      var canvas 
7        , ctx 
8        , sphereSize = 32 
9        , offsetX = 0 
10       , offsetY = 0; 
11    
12     app.init = function() { 
13       app.prepareCanvas(); 
14       app.mainloop(); 
15     }; 
16    
17     app.prepareCanvas = function() { 
18       canvas = document.querySelector('#canvas-demo-01'); 
19       ctx = canvas.getContext('2d'); 
20       ctx.fillStyle = 'rgb(0, 0, 0)'; 
21       ctx.fillRect(0, 0, canvas.width, canvas.height); 
22     }; 
23    
24     app.mainloop = function() { 
25       var i; 
26       ctx.fillStyle = 'rgba(0,0,0,0.1)'; 
27       ctx.fillRect(0, 0, canvas.width, canvas.height); 
28       for (i = 0; i < 20; i += 1) { 
29         app.displaySphere(Math.floor(Math.random() * canvas.width + 1), 
30           Math.floor(Math.random() * canvas.height + 1), 
31           Math.floor(Math.random() + 0.5)); 
32       } 
33       requestAnimationFrame(app.mainloop); 
34     }; 
35    
36     app.displaySphere = function(x, y, c) { 
37       var radgrad = ctx.createRadialGradient(offsetX + x, 
38         offsetY + y, 
39         0.5, 
40         offsetX + x, 
41         offsetY + y, 
42         sphereSize * 0.5); 
43       if (c === 0) { 
44         radgrad.addColorStop(0, '#FF0000'); 
45         radgrad.addColorStop(0.9, '#990000'); 
46         radgrad.addColorStop(1, 'rgba(0,0,0,0)'); 
47       } else { 
48         radgrad.addColorStop(0, '#0000FF'); 
49         radgrad.addColorStop(0.9, '#000099'); 
50         radgrad.addColorStop(1, 'rgba(0,0,0,0)'); 
51       } 
52       ctx.fillStyle = radgrad; 
53       ctx.fillRect(offsetX + x - sphereSize * 0.5, 
54         offsetY + y - sphereSize * 0.5, 
55         sphereSize, 
56         sphereSize); 
57     }; 
58   })(canvasDemo01); 
59    
60   canvasDemo01.init(); 
61    
62