Waving Blocks


Nice canvas effect where boxes are waving and changing colors.



Javascript file: fx_boxmania.js:
function BoxMania(canvas_ctx, width_box, height_box, num_cols, num_rows) {
    
    this.dst = canvas_ctx;
    this.w = width_box;
    this.h = height_box;
    this.j = num_rows;
    this.i = num_cols;
    this.spiner = 0;
    
    this.draw = function() {
         
         this.spiner += 2;
         
         for (this.j = -4; this.j < 19; this.j++) {
              for (this.i = 0; this.i < 20; this.i++) {
                   
                   var x = this.i * this.w + 10 + Math.floor(Math.sin((this.spiner + this.i ) * Math.PI / 360) * 30)
                   var y = this.j * this.h + 10 + Math.floor(Math.sin((this.spiner + this.i ) * Math.PI / 360) * 140);
                   
                   var ts = this.spiner + this.i * this.j + Math.sin(this.spiner % 100 * Math.PI / 360);
                   
                   var rx = parseInt(this.w * Math.sin(ts * Math.PI / 180));
                   var ry = parseInt(this.h * Math.sin(ts * Math.PI / 180));
                   
                   var sx = parseInt((this.w - rx) / 2);
                   var sy = parseInt((this.h - ry) / 2);
                   
                   var color_r = sx - ry + 20 + this.i * this.j;
                   var color_g = Math.floor(260 * Math.sin(this.spiner / 150));
                   var color_b = Math.floor(360 * Math.cos(this.spiner / 50));
                   
                   this.dst.strokeStyle = 'rgba(' + color_r + ', ' + color_g + ', ' + color_b + ', 1)';
                   this.dst.fillStyle = 'rgba(' + color_r + ', ' + color_g + ', ' + color_b + ', 0.6)';
                   
                   this.dst.beginPath();
                   this.dst.moveTo(x, y);
                   this.dst.lineTo(x + rx, y);
                   this.dst.lineTo(x + rx, y + ry);
                   this.dst.lineTo(x, y + ry);
                   this.dst.closePath();
                   this.dst.fill();
                   this.dst.stroke();
                   
              }
         }
    }
}
HTML page
<!DOCTYPE html>
<html>
 <head>
  <title>Blocks</title>
</head>
<body>

<canvas id="demo_canvas" style="display:none;" width="640" height="480"></canvas>
<script type="text/javascript" src="/files/canvas/3/fx_boxmania.js"></script>
<script type="text/javascript">

var WIDTH = 640;
var HEIGHT = 480;

var canvas;
var ctx, ctx2;
var boxes;


function init() {
    
    canvas = document.getElementById("demo_canvas");
    ctx = canvas.getContext("2d");
    boxes = new BoxMania(ctx, 40, 40, 20, 20);
    draw();
}


function draw() {
    
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, WIDTH, HEIGHT);
    boxes.draw();
    ctx.drawImage(canvas, 0, 0);
    requestAnimationFrame(draw);
}

window.onload = function () {
    init();
};
</script>
</body>
</html>



  Article "tagged" as:
  Categories: