Javascript Tutorials
Wednesday, October 28, 2015
Sunday, September 27, 2015
Flaming cursor.
HTML
CSS
background:#333;
height:400px;
width:400px;
}
JavaScript
var canvas = obj;
var ctx = canvas.getContext("2d");
//Make the canvas occupy the full page
var W = window.innerWidth, H = window.innerHeight;
canvas.width = W;
canvas.height = H;
var particles = [];
var mouse = {};
//Lets create some particles now
var particle_count = 100;
for(var i = 0; i < particle_count; i++)
{
particles.push(new particle());
}
//finally some mouse tracking
canvas.addEventListener('mousemove', track_mouse, false);
function track_mouse(e)
{
//since the canvas = full page the position of the mouse
//relative to the document will suffice
mouse.x = e.pageX;
mouse.y = e.pageY;
}
function particle()
{
//speed, life, location, life, colors
//speed.x range = -2.5 to 2.5
//speed.y range = -15 to -5 to make it move upwards
//lets change the Y speed to make it look like a flame
this.speed = {x: -2.5+Math.random()*5, y: -15+Math.random()*10};
//location = mouse coordinates
//Now the flame follows the mouse coordinates
if(mouse.x && mouse.y)
{
this.location = {x: mouse.x, y: mouse.y};
}
else
{
this.location = {x: W/2, y: H/2};
}
//radius range = 10-30
this.radius = 10+Math.random()*20;
//life range = 20-30
this.life = 20+Math.random()*10;
this.remaining_life = this.life;
//colors
this.r = Math.round(Math.random()*255);
this.g = Math.round(Math.random()*255);
this.b = Math.round(Math.random()*255);
}
function draw()
{
//Painting the canvas black
//Time for lighting magic
//particles are painted with "lighter"
//In the next frame the background is painted normally without blending to the
//previous frame
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0, 0, W, H);
ctx.globalCompositeOperation = "lighter";
for(var i = 0; i < particles.length; i++)
{
var p = particles[i];
ctx.beginPath();
//changing opacity according to the life.
//opacity goes to 0 at the end of life of a particle
p.opacity = Math.round(p.remaining_life/p.life*100)/100
//a gradient instead of white fill
var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius);
gradient.addColorStop(0, "rgba("+p.r+", "+p.g+", "+p.b+", "+p.opacity+")");
gradient.addColorStop(0.5, "rgba("+p.r+", "+p.g+", "+p.b+", "+p.opacity+")");
gradient.addColorStop(1, "rgba("+p.r+", "+p.g+", "+p.b+", 0)");
ctx.fillStyle = gradient;
ctx.arc(p.location.x, p.location.y, p.radius, Math.PI*2, false);
ctx.fill();
//lets move the particles
p.remaining_life--;
p.radius--;
p.location.x += p.speed.x;
p.location.y += p.speed.y;
//regenerate particles
if(p.remaining_life < 0 || p.radius < 0)
{
//a brand new particle replacing the dead one
particles[i] = new particle();
}
}
}
setInterval(draw, 33);
}
Saturday, September 26, 2015
Bouncing boxes.
Click below
HTML
<canvas onclick='boxes(this)'></canvas>
CSS
canvas{
background:#000;
}
JavaScript
function boxes(obj){
window.onload = function()
{
// lets get the HTML canvas element so we draw on it
var canvas = obj;
var ctx = canvas.getContext("2d")
var W = window.innerWidth, // get the width of our window
H = window.innerHeight;// get the height
// set our canvas to our size of Width and height
canvas.width = W;
canvas.height = H;
/*=========== Box class ===========*/
function Box(_x,_y)
{
// the X/Y position
this.x = _x;
this.y = _y;
// lets give it velocity X and Y
this.xVel = 10 + Math.random()*20;
this.yVel = 1;
// the box width and height
this.width = 20
this.height = 20;
// random colors for our box
this.r = Math.round(Math.random()*255);
this.g = Math.round(Math.random()*255);
this.b = Math.round(Math.random()*255);
this.rgba = "rgba("+this.r+","+this.g+","+this.b+",1)";
// lets make draw method for our box
this.draw = function()
{
ctx.strokeStyle = this.rgba;
ctx.strokeRect(this.x,this.y,this.width,this.height);
this.update();
}
// function that handle our logics for our box
this.update = function()
{
// lets check if the ball get out of our screen and when
// it does that, make it bounce
// check the left window border
if(this.x < 0) {
this.x = 0; // set its position to 0
this.xVel *= -1; // make it bounce
}
// check the right border
if(this.x > W - this.width)
{
this.x = W - this.width; // set its position to 0
this.xVel *= -1; // make it bounce
}
// check the top border
if(this.y < 0) {
this.y = 0; // this is what happen when u copy/paste
this.yVel *= -1; // make it bounce
}
// the reason why we did this if function so the boxes dont
// try to add y by its velocity when its reach bottom
// cause it will cause it to spazz
// now we add gravity
if(this.y < H - this.height)
this.yVel += .25;
// check the bottom border
if(this.y > H - this.height)
{
// when it bounce off the bottom decrease the ball speed
this.xVel *= .5
this.yVel *= .5
this.y = H - this.height; // set its position to 0
this.yVel *= -1; // make it bounce
}
// move add speed to our x/y
this.x += this.xVel;
this.y += this.yVel;
}
}
// lets make array of boxes
var boxes = [];
// Function to draw stuff on our screen :)
function draw()
{
// Background
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(0,0,0,0.5)"
ctx.fillRect(0,0,W,H);
ctx.globalCompositeOperation = "lighter"
// loop through the boxes and draw them
for(i=0; i < boxes.length; i++)
boxes[i].draw();
update();
}
// Function for our logic
function update()
{
// loop through the boxes and draw them
for(i=0; i < boxes.length; i++)
boxes[i].update();
}
// add box every minute we specify
setInterval(function(){
boxes.push( new Box(0,0))
},1000);
// set interval so we can draw then update our drawing
// every 30 milisecond
setInterval(draw,30);
}
}
Wednesday, September 23, 2015
Pixels.

By Code pen
Click below
HTML
<canvas onclick='abc(this)'></canvas>
CSS
canvas{
background:#333;
}
JavaScript
function abc(obj){
var _canvas = obj;
var _ctx = _canvas.getContext('2d');
var _rotation = 0;
var _offset = 1;
var _offsetInc = 1;
function render() {
_ctx.restore();
_ctx.fillStyle = 'rgba(0,0,0,0.1)';
_ctx.fillRect(0,0,window.innerWidth, window.innerHeight);
_ctx.save();
_ctx.translate(window.innerWidth/2, window.innerHeight/2);
_ctx.rotate(_rotation+= 0.1);
_ctx.translate(-window.innerWidth/2, -window.innerHeight/2);
if (_offset <= 3) {
_offset = 3;
_offsetInc = 3;
}
if (_offset >= 3) {
_offset = 3;
_offsetInc = -3;
}
for (var i = 0; i < 1000; i+= 10) {
_ctx.fillStyle = 'white';
for (var radius = 20; radius < window.innerHeight/2; radius += _offset*2) {
_ctx.fillRect(
(Math.tan(i)*radius + window.innerWidth/2),(Math.sin(i)*radius + window.innerWidth/2),4,4);
}
}
setTimeout(render, 60);
}
function addEventListeners() {
window.addEventListener('resize', resizeHandler);
}
function resizeHandler() {
_canvas.width = window.innerWidth;
_canvas.height = window.innerHeight;
}
function init() {
render();
resizeHandler();
addEventListeners();
}
init();
}
Matrix.
Click below
HTML
<canvas id="c"></canvas>
CSS
canvas{
background:#333;
}
JavaScript
var c = document.getElementById("c");
var ctx = c.getContext("2d");
//making the canvas full screen
c.height = window.innerHeight;
c.width = window.innerWidth;
//chinese characters - taken from the unicode charset
var chinese = "田由甲申甴电甶男甸甹町画甼甽甾甿畀畁畂畃畄畅畆畇畈畉畊畋界畍畎畏畐畑";
//converting the string into an array of single characters
chinese = chinese.split("");
var font_size = 10;
var columns = c.width/font_size; //number of columns for the rain
//an array of drops - one per column
var drops = [];
//x below is the x coordinate
//1 = y co-ordinate of the drop(same for every drop initially)
for(var x = 0; x < columns; x++)
drops[x] = 1;
//drawing the characters
function draw()
{
//Black BG for the canvas
//translucent BG to show trail
ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#0F0"; //green text
ctx.font = font_size + "px arial";
//looping over drops
for(var i = 0; i < drops.length; i++)
{
//a random chinese character to print
var text = chinese[Math.floor(Math.random()*chinese.length)];
//x = i*font_size, y = value of drops[i]*font_size
ctx.fillText(text, i*font_size, drops[i]*font_size);
//sending the drop back to the top randomly after it has crossed the screen
//adding a randomness to the reset to make the drops scattered on the Y axis
if(drops[i]*font_size > c.height && Math.random() > 0.975)
drops[i] = 0;
//incrementing Y coordinate
drops[i]++;
}
}
setInterval(draw, 33);
Fire works.
HTML
<canvas id="canvas">Canvas is not supported in your browser.</canvas>
CSS
canvas {
cursor: crosshair;
background: #333;
}
JavaScript
window.requestAnimFrame = ( function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ) {
window.setTimeout( callback, 1000 / 60 );
};
})();
// now we will setup our basic variables for the demo
var canvas = document.getElementById( 'canvas' ),
ctx = canvas.getContext( '2d' ),
// full screen dimensions
cw = 400,
ch = 400,
// firework collection
fireworks = [],
// particle collection
particles = [],
// starting hue
hue = 120,
// when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
limiterTotal = 5,
limiterTick = 0,
// this will time the auto launches of fireworks, one launch per 80 loop ticks
timerTotal = 80,
timerTick = 0,
mousedown = false,
// mouse x coordinate,
mx,
// mouse y coordinate
my;
// set canvas dimensions
canvas.width = cw;
canvas.height = ch;
// now we are going to setup our function placeholders for the entire demo
// get a random number within a range
function random( min, max ) {
return Math.random() * ( max - min ) + min;
}
// calculate the distance between two points
function calculateDistance( p1x, p1y, p2x, p2y ) {
var xDistance = p1x - p2x,
yDistance = p1y - p2y;
return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}
// create firework
function Firework( sx, sy, tx, ty ) {
// actual coordinates
this.x = sx;
this.y = sy;
// starting coordinates
this.sx = sx;
this.sy = sy;
// target coordinates
this.tx = tx;
this.ty = ty;
// distance from starting point to target
this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
this.distanceTraveled = 0;
// track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails
this.coordinates = [];
this.coordinateCount = 3;
// populate initial coordinate collection with the current coordinates
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
this.angle = Math.atan2( ty - sy, tx - sx );
this.speed = 2;
this.acceleration = 1.05;
this.brightness = random( 50, 70 );
// circle target indicator radius
this.targetRadius = 1;
}
// update firework
Firework.prototype.update = function( index ) {
// remove last item in coordinates array
this.coordinates.pop();
// add current coordinates to the start of the array
this.coordinates.unshift( [ this.x, this.y ] );
// cycle the circle target indicator radius
if( this.targetRadius < 8 ) {
this.targetRadius += 0.3;
} else {
this.targetRadius = 1;
}
// speed up the firework
this.speed *= this.acceleration;
// get the current velocities based on angle and speed
var vx = Math.cos( this.angle ) * this.speed,
vy = Math.sin( this.angle ) * this.speed;
// how far will the firework have traveled with velocities applied?
this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );
// if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached
if( this.distanceTraveled >= this.distanceToTarget ) {
createParticles( this.tx, this.ty );
// remove the firework, use the index passed into the update function to determine which to remove
fireworks.splice( index, 1 );
} else {
// target not reached, keep traveling
this.x += vx;
this.y += vy;
}
}
// draw firework
Firework.prototype.draw = function() {
ctx.beginPath();
// move to the last tracked coordinate in the set, then draw a line to the current x and y
ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
ctx.stroke();
ctx.beginPath();
// draw the target for this firework with a pulsing circle
ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
ctx.stroke();
}
// create particle
function Particle( x, y ) {
this.x = x;
this.y = y;
// track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
this.coordinates = [];
this.coordinateCount = 5;
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 10 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 1;
// set the hue to a random number +-20 of the overall hue variable
this.hue = random( hue - 20, hue + 20 );
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}
// update particle
Particle.prototype.update = function( index ) {
// remove last item in coordinates array
this.coordinates.pop();
// add current coordinates to the start of the array
this.coordinates.unshift( [ this.x, this.y ] );
// slow down the particle
this.speed *= this.friction;
// apply velocity
this.x += Math.cos( this.angle ) * this.speed;
this.y += Math.sin( this.angle ) * this.speed + this.gravity;
// fade out the particle
this.alpha -= this.decay;
// remove the particle once the alpha is low enough, based on the passed in index
if( this.alpha <= this.decay ) {
particles.splice( index, 1 );
}
}
// draw particle
Particle.prototype.draw = function() {
ctx. beginPath();
// move to the last tracked coordinates in the set, then draw a line to the current x and y
ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
ctx.stroke();
}
// create particle group/explosion
function createParticles( x, y ) {
// increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though
var particleCount = 30;
while( particleCount-- ) {
particles.push( new Particle( x, y ) );
}
}
// main demo loop
function loop() {
// this function will run endlessly with requestAnimationFrame
requestAnimFrame( loop );
// increase the hue to get different colored fireworks over time
hue += 0.5;
// normally, clearRect() would be used to clear the canvas
// we want to create a trailing effect though
// setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely
ctx.globalCompositeOperation = 'destination-out';
// decrease the alpha property to create more prominent trails
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect( 0, 0, cw, ch );
// change the composite operation back to our main mode
// lighter creates bright highlight points as the fireworks and particles overlap each other
ctx.globalCompositeOperation = 'lighter';
// loop over each firework, draw it, update it
var i = fireworks.length;
while( i-- ) {
fireworks[ i ].draw();
fireworks[ i ].update( i );
}
// loop over each particle, draw it, update it
var i = particles.length;
while( i-- ) {
particles[ i ].draw();
particles[ i ].update( i );
}
// launch fireworks automatically to random coordinates, when the mouse isn't down
if( timerTick >= timerTotal ) {
if( !mousedown ) {
// start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen
fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
timerTick = 0;
}
} else {
timerTick++;
}
// limit the rate at which fireworks get launched when mouse is down
if( limiterTick >= limiterTotal ) {
if( mousedown ) {
// start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
fireworks.push( new Firework( cw / 2, ch, mx, my ) );
limiterTick = 0;
}
} else {
limiterTick++;
}
}
// mouse event bindings
// update the mouse coordinates on mousemove
canvas.addEventListener( 'mousemove', function( e ) {
mx = e.pageX - canvas.offsetLeft;
my = e.pageY - canvas.offsetTop;
});
// toggle mousedown state and prevent canvas from being selected
canvas.addEventListener( 'mousedown', function( e ) {
e.preventDefault();
mousedown = true;
});
canvas.addEventListener( 'mouseup', function( e ) {
e.preventDefault();
mousedown = false;
});
// once the window loads, we are ready for some fireworks!
window.onload = loop;