Change canvas element properties on mouse click - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Change canvas element properties on mouse click

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){//from   w  w w.ja  v a 2s.  c o m
var canvas = document.getElementById("canvas");
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.width = window_width;
canvas.height = window_height;
var ctx = canvas.getContext('2d');
var circles = new Array();
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
function Item(speed, size, x, y, opacity, lineWidth) {
   this.speed       = speed;
   this.size       = size;
   this.xPos       = x;
   this.yPos       = y;
   this.opacity   = opacity;
   this.lineWidth   = lineWidth;
   this.counter = 0;
   var signHelper = Math.floor(Math.random() * 2);
   if (signHelper == 1) {
      this.sign = -1;
   } else {
      this.sign = 1;
   }
}
Item.prototype.update = function () {
   this.counter += this.sign * this.speed;
   ctx.beginPath();
   var currentX       = this.xPos + Math.cos(this.counter / 100) * 134.5;
   var currentY       = this.yPos + Math.sin(this.counter / 100) * 4.5;
   var currentY       = 0;
   var currentSize    = this.size;

   ctx.beginPath();
   ctx.rect(currentX, currentY, currentSize, currentSize);
   ctx.fillStyle = 'rgba(255, 255, 255,' + this.opacity + ')';
   ctx.fill();
};
function makeElements() {
   for (var i = 0; i < 10; i++) {
      var x          =    Math.round(-400 + Math.random() * window_width);
      var y          =    Math.round(-400 + Math.random() * window_height);
      var y          =    0;
      var speed       =    0.05 + Math.random() * 3;
      var size       =    100 + Math.random() * 1000;
      var size       =    canvas.height;
      var opacity    =    Math.random() * 0.1;
      var lineWidth    =    100+ Math.random() * 1000;
      var item = new Item(speed, size, x, y,opacity, lineWidth);
      circles.push(item);
   }
   draw();
}
makeElements();
function draw() {
   ctx.clearRect(0, 0, window_width, window_height);
   for (var i = 0; i < circles.length; i++) {
      var myCircle = circles[i];
      myCircle.update();
   }
   requestAnimationFrame(draw);
}
$('#btn').click(function(){
    circles[1].size = Math.random() * 1000;
});
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" style="background: #333;"></canvas> 
      <button id="btn">click</button>  
   </body>
</html>

Related Tutorials