Skip to content

Instantly share code, notes, and snippets.

@pixlpa
Created July 23, 2015 05:54
Show Gist options
  • Save pixlpa/04038fb649b654345cca to your computer and use it in GitHub Desktop.
Save pixlpa/04038fb649b654345cca to your computer and use it in GitHub Desktop.
HTML5 Canvas animated transition overlay for slow loading images.
function glitchTransition(){
this.canvas = document.getElementById("transition");
this.c = this.canvas.getContext('2d');
this.img = document.createElement('img');
this.img.onerror = function(e){
e.src = '';
}
this.nextimg = "";
//this.feed = document.createElement('img');
this.tt = 0;
this.active = true;
//loaded should be set to true using the image's 'onload' event handler and set to false before calling activate()
this.loaded = true;
this.time = 12; //minimum frames to run the transition for
//smears a rect of the existing canvas.
this.shiftpix = function(ticks){
var b = 0;
var sx = Math.random()*400;
var sy = Math.random()*360;
var dx = Math.floor(Math.random()*20)-10;
var dy = Math.floor(Math.random()*20)-10;
var tx = Math.random()*200;
var ty = Math.random()*100;
for(b=0;b<ticks;b++){
this.c.drawImage(this.canvas,sx+dx*b,sy+dy*b,tx,ty,sx,sy,tx,ty);
}
};
//draws a random rect from previous image
this.basepix = function(ticks){
var b = 0;
var sx = Math.random()*400;
var sy = Math.random()*360;
var dx = Math.floor(Math.random()*200)-100;
var dy = Math.floor(Math.random()*200)-100;
var tx = Math.random()*200;
var ty = Math.random()*100;
this.c.drawImage(this.img,sx,sy,tx,ty,sx+dx,sy+dy,tx,ty);
};
// The activate method is used to start the transition and set next image
this.activate = function(imgx){
this.nextimg = imgx;
this.active = true;
this.tt = 0;
}
// Deactivate is called internally when "loaded" is set to true, but can be used to kill the effect as well.
this.deactivate = function(){
this.c.clearRect(0,0,400,360);
this.active = 0;
this.img.src = this.nextimg;
}
this.draw = function(){
this.c.fillStyle = randomcolor();
this.c.fillRect(Math.random()*400,Math.random()*360,Math.random()*200,Math.random()*200);
this.basepix();
this.shiftpix(4);
this.c.clearRect(Math.random()*400,Math.random()*360,Math.random()*200,Math.random()*200);
this.basepix();
this.shiftpix(4);
this.c.clearRect(Math.random()*400,Math.random()*360,Math.random()*200,Math.random()*200);
this.basepix();
this.shiftpix(4);
this.tt++;
if (this.active && this.tt>this.time && this.loaded) this.deactivate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment