canvas mouse follow with velocity
need to add gradient mask from google
by Nick Hulea
HTML
<canvas id="canvas" width="480" height="360"></canvas>
JavaScript
var Stage = function (id, color, rate) {
this.rate = Math.round(1000 / rate);
this.canvas = document.getElementById(id);
this.canvas.stage = this;
this.context = this.canvas.getContext("2d");
this.bgColor = color;
this.rect = this.canvas.getBoundingClientRect();
this.mouseX = 0;
this.mouseY = 0;
this.children = [];
this.init = function () {
this.context.fillStyle = this.bgColor;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
};
this.init();
this.addChild = function (obj) {
this.init();
this.children.push(obj);
obj.stage = this;
obj.draw();
};
this.update = function () {
this.init();
for (var i = 0; i < this.children.length; i++) {
this.children[i].draw();
}
};
this.canvas.onmousemove = function (e) {
this.stage.mouseX = e.clientX - this.stage.rect.left;
this.stage.mouseY = e.clientY - this.stage.rect.top;
};
};
var Circle = function (radius) {
//this.color = color;
this.x = 10;
this.y = 0;
this.radius = radius;
this.draw = function () {
var context = this.stage.context;
// create radial gradient
var grd = context.createRadialGradient(this.x, this.y, 5, this.x, this.y, 100);
// light blue
grd.addColorStop(0, 'rgba(255,255,255,0)');
// dark blue
grd.addColorStop(1, 'rgba(255,255,255,1)');
context.fillStyle = grd;
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
context.closePath();
context.fill();
};
};
var stage = new Stage("canvas", "#ccc", 30);
var circle = new Circle(30);
stage.addChild(circle);
setInterval(function () {
circle.x += (stage.mouseX - circle.x) * 0.1;
circle.y += (stage.mouseY - circle.y) * 0.1;
stage.update();
}, stage.rate);