Create your portfolio gallery using html5 canvas – tutorial

In this tutorial we will build a photo gallery and enhance it with html5 canvas and css3 transitions. See the demo and try the hover effect. The grayscale “copies” of the images are created with canvas and we use pure css3 for the smooth changes.

Photo gallery with html5 canvas

Download the source files

Portfolio gallery with canvas
.zip 0.25MB

Step 1 : Html markup

Let’s start with a simple markup, each portfolio entry being an element of an unordered list.

<!DOCTYPE html>
	<meta charset="UTF-8" />
	<title>Gallery :: Tutorial by PeHaa </title>
	<script src=""></script>
	<div id="wrap">
		<ul id="gallery">
			<li><a href=""><img src="images/flo1.jpg"><div>Spring flowers 1</div></a></li>
			<li><a href=""><img src="images/lights2.jpg"><div>City lights 1</div></a></li>
			<li><a href=""><img src="images/flo3.jpg"><div>Spring flowers 2</div></a></li>
			<li><a href=""><img src="images/lights1.jpg"><div>City lights 2</div></a></li>
			<li><a href=""><img src="images/flo2.jpg"><div>Spring flowers 3</div></a></li>
			<li><a href=""><img src="images/lights3.jpg"><div>City lights 3</div></a></li>
		<p>Photos by <a href="">Pinkonhead</a></p>

Step 2: Basic styles

We start our stylesheet with a basic reset.

html, body, div, span, h1, h2,  p, a,  ul, li, img
{margin: 0; padding: 0;
border: 0; outline: 0;
font-size: 100%;background: transparent;}
ul {list-style: none;}
:focus {outline: 0;}
a {text-decoration:none;}

We will use 300px x 300px images. The main containing element #wrap is centered up (margin: 0 auto) and given the width of 1020px (=340 x 3).
The list items are given float : left and are positioned relatively. The image title is wrapped in a div element that slides up on hover. To achieve a smooth effect we apply a css3 transition.
(Note that for the simplicity of this tutorial I don’t use any vendor prefixes. Therefore, you’ll find them in the source file to download).

#wrap {
  width: 1020px; 
  margin: 0 auto;
li {
  box-shadow:0 0 5px rgba(0,0,0,.35);
li div {
  padding: 0 10px;
  transition:height 1s;
li:hover div {

Click on the image to below to see the result at the current stage.

Photo gallery with canvas

Step 3: Canvas

Now, we will make use of the html5 canvas element to draw the grayscale versions of our images. Below you’ll find a createCanvas custom function that creates a canvas element, takes a copy of an image, performs the conversion and draws it to the canvas and finally inserts the canvas to the DOM where desired. With .each() method the createCanvas function is iterated across all images within the #gallery list.

$(window).load(function() {

	  $('#gallery img').each(function() {


	  function createCanvas(image) {

	    var canvas = document.createElement('canvas');
	    if (canvas.getContext) {
	      var ctx = canvas.getContext("2d");

// specify canvas size
	      canvas.width = image.width;
	      canvas.height = image.height;

// Once we have a reference to the source image object we can use 
// the drawImage(reference, x, y) method to render it to the canvas. 
//x, y are the coordinates on the target canvas where the image should be placed.
	      ctx.drawImage(image, 0, 0);

// Taking the image data and storing it in the imageData array. 
//You can read the pixel data on a canvas using the getImageData() method. 
// Image data includes the colour of the pixel (decimal, rgb values) and alpha value. 
// Each color component is represented by an integer between 0 and 255. 
// contains height x width x 4 bytes of data, with index values ranging from 0 to (height x width x 4)-1.
	      var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height),
	          pixelData =;

// Loop through all the pixels in the imageData array, and modify
// the red, green, and blue color values.
	      for (var y = 0; y < canvas.height; y++) {
	        for (var x = 0; x < canvas.width; x++) {

// You can access the color values of the (x,y) pixel as follows :
	          var i = (y * 4 * canvas.width) + (x * 4);

// Get the RGB values.
	          var red = pixelData[i];
	          var green = pixelData[i + 1];
	          var blue = pixelData[i + 2];

// Convert to grayscale. One of the formulas of conversion (e.g. you could try a simple average (red+green+blue)/3)   
	          var grayScale = (red * 0.3) + (green * 0.59) + (blue * .11);

	          pixelData[i] = grayScale;
	          pixelData[i + 1] = grayScale;
	          pixelData[i + 2] = grayScale;

// Putting the modified imageData back on the canvas.
	      ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);

// Inserting the canvas in the DOM, before the image:
	      image.parentNode.insertBefore(canvas, image);

Step 4: Styling the canvas

If you look into the generated code source you’ll find

<ul id="gallery">
	<li><a href=""><canvas width="300" height="300"></canvas><img src="images/flo1.jpg"><div>Spring flowers 1</div></a></li>
	<li><a href=""><canvas width="300" height="300"></canvas><img src="images/lights2.jpg"><div>City lights 1</div></a></li>

Let’s add some styling to define the canvas behavior in normal and hover state:

canvas {
  transition:opacity 1s .2s;
li:hover canvas {

And that’s it ! This example will not work in Internet Explorer versions below 9. You could provide an alternative solution using grayscale filter and adding some jQuery to recreate the transition effect on hover – but this part is not covered in this tutorial.

The beautiful photos featured here were taken by Pinkonhead, and are shared as freebies on her blog. Enjoy.

Create a fancy responsive image-on-hover effect

In this tutorial we will create a fancy image-on-hover effect. We’ll use pure css3 and provide a jQuery solution for the browsers that do not support opacity and transitions. We will also take care that it works responsively.

Two version of an image

Download the source files

Fancy responsive image-on-hover effect
.zip 0.2MB

Step 1 : Photoshop

We have to prepare two versions of the image : the image we want to see on hover and its desaturated copy. Mine are 845px x 515px.

Two version of an image

Step 2 : Let’s start with the html markup

<div id="wrap">
          <img src="img/tut1_desaturated.jpg"/>
          <span class="shadow"></span>
          <img class="onhover" src="img/tut1_color.jpg"/>

Step 3: Basic styles

We start our stylesheet with a basic reset.

html, body, div, span, h1, h2,  p, a,  ul, li, img
{margin: 0; padding: 0;
border: 0; outline: 0;
font-size: 100%;background: transparent;}
ul {list-style: none;}

The main containing element #wrap is centered up and given the specific width 865 px = 845px (image size) + 2x10px (borders size).
The div that contains the images is given position:relative (to properly position the two versions of the image) and overflow hidden (we will size up and rotate our images and we want to hide the exceeding parts).

#wrap { width: 865px; margin: 0 auto;}
ul {margin-top:50px; }
li div {width:845px; height:515px; overflow:hidden; position:relative;
border:10px solid white; box-shadow: 0 2px 5px  rgba(0,0,0,.4);}

Step 4: Grayscale to color transition (see demo)

The img element is positioned relatively, the colored version (.onhover) is given 0 opacity and absolute position. When the containing div is being hovered over the opacity of .onhover element changes to 1. To make the transition smooth we apply the transition property to img. (For simplicity I decided to omit all vendor prefixes).

img {position:relative; top:0;left:0;
transition:all 1.5s .5s; }
img.onhover {opacity:0;position:absolute;}
li div:hover img.onhover {opacity:1;}

To deepen the effect of transition between the normal and hover state we will add a fading out inner shadow (span.shadow):

.shadow {position:absolute; top:0; left:0; opacity:1; background:transparent;
width:100%; height:100%;
box-shadow: inset 0 0 60px 20px rgba(37,27,23,.5);
transition:opacity 1.5s .5s;}
li div:hover .shadow {opacity:0;}

Step 5: Let’s add scaling and rotation (see demo)

We just have to add the transform property, specify the transform origin as well as the transform parameters in hover state.

img {position:relative; top:0;left:0;
transition:all 1.5s .5s;
transform: rotate(-4deg) scale(1.2);
transform-origin:50% 50%;}

li div:hover img {transform: scale(1) rotate(0);}

Step 6: And what if we want it responsive ? (see demo)

First let’s modify a little bit the style of #wrap and the li div to keep them flexible. In the latter case we just no longer specify the height and width of the element.

#wrap { max-width: 865px; margin: 0 auto; width:95%;}
li div { overflow:hidden; position:relative;
border:10px solid white; box-shadow: 0 2px 5px rgba(0,0,0,.4);}

We have also to modify the styling of the img element – we add three new properties to the img element.

img {max-width:auto; vertical-align:bottom; width:100%;}

Step 7: jQuery solution

We will add a jQuery solutions for IE.

<!--[if lt IE 9]><script>
<script src=""></script>
	$(document).ready(function() { 
$('li div').hover(function(){

You can also go further and recreate the full transition with jQuery animate function.

And that’s it. I hope you got inspired by this example – it’s your turn to play with css transitions. Enjoy !

Intriguing animate-on-scroll effect – jQuery tutorial

I suppose that I was not the only one to become speechless in front of the Nizo for iPhone website.
In this tutorial we try to recreate the intriguing scrolling effect. We’ll go for simplicity : 5 objects to animate and linear movement, no easing. The basis that opens the door for further elaboration.

Click here to see the demo.
My herb garden preview

Download the source files

My herb garden
.zip 0.4MB

We’ll start with the html structure :

<!DOCTYPE html>
<meta charset="UTF-8" />
<title>My herb garden</title>
<div id="wrap_out">
  <div id='wrap'>
      <h1>My <em>herb</em> garden</h1>
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum id ligula porta felis euismod semper.</p>
    <div id="separation">
      <div>Scroll <em>down</em></div>
      <img src="images/herbes.jpg" width="592" height="350" alt="Herbes"> </div>
      <div  id="coriander" class="element">
        <img src="images/coriander1.jpg" width="286" height="232" alt="Coriander">
        <p>Cras mattis consectetur purus sit amet fermentum. Cras mattis consectetur purus sit amet fermentum. Cras mattis consectetur purus sit amet fermentum.</p>
      <div  id="rosemary" class="element">...</div>
      <div  id="lemonbalm" class="element">...</div>
      <div  id="chives" class="element">...</div>
      <div  id="basil" class="element">...</div>
    <footer> <a href=""> by <em>PeHaa</em> 2011</a> </footer>

The document is composed of 4 elements header, #separation, section and footer, contained within two divs : #wrap_out and #wrap.
The stylesheet begins with a simple css reset and the @font-face declaration

body, div, h1, h2, form, fieldset, input, textarea, footer, p, img {
	margin: 0; padding: 0; border: 0; outline: none;
a { text-decoration:none; color: #fff;}

 @font-face {
 font-family: 'DeibiRegular';
 src: url('deibi-webfont.eot');
 src: url('deibi-webfont.eot?#iefix') format('embedded-opentype'),  url('deibi-webfont.woff') format('woff'),  url('deibi-webfont.ttf') format('truetype'),  url('deibi-webfont.svg#DeibiRegular') format('svg');
 font-weight: normal;
 font-style: normal;

Right now, the important point is to set width : 100% and overflow-x: hidden for the #wrap_out. The #wrap element centers the content of the page.
section is positioned relatively and the animated herbs (class="element") are positioned absolutely.
Let’s continue with our stylesheet :

body { 
	font-family:'DeibiRegular', Helvetica, Arial, sans-serif;
	background:#f2f2f2 url('images/bg.jpg');
	color: #fff; width:100%;
#wrap_out {width:100%; overflow-x:hidden;}
#wrap {width: 960px; margin: 0 auto; z-index:1;position:relative;}

header {display:block;z-index:2 position:relative;}
header p {display:block; font-size:30px; padding: 70px 60px 0px;}
h1 {text-align:center;font-size:130px; margin-top: 30px; text-shadow: 0 0 60px #889473;}
h1 em {color: #f5f187;font-style: normal;}

#separation {margin: 0 auto;width: 592px;z-index:-1;position:relative;}

section {position:relative; margin-top: 120px;display:block}

.element { position:absolute; display:block;}
.element#coriander {top:0px; left:30px; width: 286px; height: 272px;}
.element#rosemary {top:40px; left: 335px; width: 370px; height: 183px;}
.element#chives {top : 0px; right:30px; width: 197px; height: 514px;}
.element#lemonbalm {left: 30px; top:280px; width:265px; height: 233px;}
.element#basil {right: 255px; top:250px; width:368px; height: 263px;}

footer {margin-bottom: 10px;text-align:center;font-size: 30px; display:block}

The idea is to encourage the visitor to scroll down by positioning the #separation element at the bottom of the page. We want the #separation to stay there when the window is resized but to move up when we start to scroll down. A possible way to do that is to make the height of the header element dependent on the height of the window browser :

$(document).ready(function () {
    var myHeight;

    function init() {
        myHeight = $(window).height();
        $('header').css('height', myHeight - 300);
    $(window).resize(function () {


To animate the .element we’ll go simple and use a linear function to move it from its initial position to its target position. We assign four parameters (its initial and final coordinates) to each element :

$('.element').each(function(i) {
			var myElement =$(this);
				switch (i)
				{ case 0 :'params', {top0 : -1300, x0 : -2600, top1: $(this).css('top'), x1: $(this).css('left')}); 
				case 1 :'params', {top0 : 0, x0 : -930, top1: $(this).css('top'), x1: $(this).css('left')}); 
				case 2 :'params', {top0 : 280, x0 : -1030, top1: $(this).css('top'), x1: $(this).css('left')});
				 case 3 :'params', {top0 : -1200, x0 : -2330, top1: $(this).css('top'), x1: $(this).css('right')}); 
				case 4 :'params', {top0 : 250, x0 : -530, top1: $(this).css('top'), x1: $(this).css('right')}); 

What happens when we scroll ? The top property of each element and the left (for coriander, rosemary and lemon bald) or right (for chives and basil) changes as a function of the scroll position :

$(window).scroll(function () {
var s_max = myHeight / 2 + 500;
    function move(p0, p1, s) {
        return Math.min((-p0 + p1) / s_max * s + p0, p1);
    var scrollTop = parseInt($(window).scrollTop());
    $('.element').each(function (i) {

        var myX = move($(this).data('params').x0, parseInt($(this).data('params').x1), scrollTop),
            myY = move($(this).data('params').top0, parseInt($(this).data('params').top1), scrollTop);
if (i < 3) {
                left: myX + 'px',
                top: myY + 'px'
        } else {
                right: myX + 'px',
                top: myY + 'px'

move is a function of the scroll value and has two parameters : initial (p0) and final (p1) position of an element.
Before we start scrolling, s = 0, move is equeal to p0. When scroll reaches s_max, the value of move is p1. The min operator prevents further movement.
As I said this is one of the simplest possible solutions.
What is s_max ? I wanted the animation to finish once the elements are verticaly centered in the middle of the window (I’m not pixel perfect here).
Where is that point ? Imagine that we don’t animate our elements and that they are in their final positions. Notice that we have to scroll down 500px (see the scheme below), to see the top of the second row of our herbs. If we scroll down a half height of a window more we will see them in the middle.
My herb garden preview
We want to be sure that the page is high enough so that the elements could reach their final positions. To assure that we will make the property height of section dependent on the height of the browser window, in this case we need to scroll $(window).height/2 + 500. We have 240px above the section (120px + 120px). The minimum height of section is then $(window).height/2 + 260. We add a line to the init function

function init() {
    myHeight = $(window).height();
    $('header').css('height', myHeight - 300);
    $('section').css('min-height', Math.max(myHeight / 2 + 260, 600));

It was tested in Safari, Firefox, Chrome, Opera, IE7 and IE8. It works in the last two if you don’t forget to add

<!--[if IE]>
	<script src=""></script>

I hope you find it useful. Please bookmark and share.
Let me know what you think – I’m looking forward to your comments. Thanks.

create a unique contact form with css3 transitions

Inspired by the contact form on Clear Span Media website I decided to recreate an effect of a letter sliding out from an envelope on mouse hover. You may see the demo here.
contact form preview

Download the source files

Contact form
.zip 330 kB

It works in browsers supporting css3 transitions. In IE the envelope is not visible, I certainly could have played a bit more with jQuery to reproduce a similar effect, but it’s not a part of this tutorial.
Let’s start with the html structure:

<!DOCTYPE html>
<meta charset="utf-8" />
<title>Contact Form</title>
	<div id="wrap">
		<h1>Send a message</h1>
		<div id='form_wrap'>
				<p>Hello Joe,</p>
				<label for="email">Your Message : </label>
				<textarea  name="message" value="Your Message" id="message" ></textarea>
				<label for="name">Name: </label>
				<input type="text" name="name" value="" id="name" />
				<label for="email">Email: </label>
				<input type="text" name="email" value="" id="email" />
				<input type="submit" name ="submit" value="Now, I send, thanks!" />

The idea is as follows (I tried to illustrate it in the scheme below): the #form_wrap is positioned relatively (top:0), with the envelope fixed to its bottom. The form is positioned relatively, with top:200px. The overlay is set to hidden for both form and #form_wrap. When mouse enters the #form_wrap its height and the height of form increase both of 350px, at the same time the top property of the #form_wrap changes to top:-200px.
contact scheme
We will need an envelope cut into two parts, the top part, visible over the letter (after.png) and the bottom part (before.png) partially covered by the letter. You’re welcome to use the .ai file available here.
envelopes Let’s start to complete the stylesheet:
contact schemeNext, we’ll add some styling to the form elements:

label {
			margin: 11px 20px 0 0; 
 			font-size: 16px; color: #b3aba1;
			text-transform: uppercase; 
			text-shadow: 0px 1px 0px #fff;
input[type=text], textarea {
		font: 14px normal normal uppercase helvetica, arial, sans-serif;
		color: #7c7873;background:none;
		width: 380px; height: 36px; padding: 0px 10px; margin: 0 0 10px 0;
		border:1px solid #f8f5f1;
		-moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;
		-moz-box-shadow: inset 0px 0px 1px #726959;
                -webkit-box-shadow:  inset 0px 0px 1px #b3a895; 
                box-shadow:  inset 0px 0px 1px #b3a895;
textarea { height: 80px; padding-top:14px;}
textarea:focus, input[type=text]:focus {background:rgba(255,255,255,.35);}
#form_wrap input[type=submit] {
		position:relative;font-family: 'YanoneKaffeesatzRegular'; 
		font-size:24px; color: #7c7873;text-shadow:0 1px 0 #fff;
		width:100%; text-align:center; opacity:0;
		cursor: pointer;
		-moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; 
#form_wrap:hover input[type=submit] {z-index:1;opacity:1;}
#form_wrap:hover input:hover[type=submit] {color:#435c70;}

So far we haven’t used the transition, click here to see where we are.

We will add the same transition to form and #form_wrap. The four parameters correspond to the transition property, duration, timing function and its delay.

  -webkit-transition: all 1s ease-in-out .3s;
  -moz-transition: all 1s ease-in-out .3s;
  -o-transition: all 1s ease-in-out .3s;
  transition: all 1s ease-in-out .3s;

Then we’ll add another transition to the input[type=submit] element. The first set of settings corresponds to the behavior when mouse leaves the #form_wrap, the second when it hovers the #form_wrap. I wanted to make sure that the submit element does not appear until the form and #form_wrap transition is finished. On the other hand it starts to disappear immediately when mouse leaves #form_wrap.

	#form_wrap input[type=submit] {
		-webkit-transition: opacity 0.6s ease-in-out 0s;
		-moz-transition: opacity .6s ease-in-out 0s;
		-o-transition: opacity .6s ease-in-out 0s;
		transition: opacity .6s ease-in-out 0s; 
	#form_wrap:hover input[type=submit] {
		-webkit-transition: opacity .5s ease-in-out 1.3s;
		-moz-transition: opacity .5s ease-in-out 1.3s;
		-o-transition: opacity .5s ease-in-out 1.3s;
                transition: opacity .5s ease-in-out 1.3s;

It’s almost ready, I will just add some jQuery so as it works in IE. The transition is similar, but not exactly the same:

<!--[if IE]><script>
	$(document).ready(function() { 
            $("#form_wrap").prepend( '<div id="before"></div>').append( '<div id="after"</div>');
	         $(this).stop(true, false).animate({
	              height : '836px',
	              top : '-200px'
	         }, 2000); 	
            $('form').stop(true, false).animate({
		height : '580px'
		}, 2000, function(){
                         $('#form_wrap input[type=submit]').css({'z-index' : '1', 'opacity' : '1'})} ) }, function() {
		$('#form_wrap input[type=submit]').stop(true, true).css({ 'opacity' : '0'})
	        $(this).stop(true, false).animate({
			height : '446px',
			top : '0px'

		}, 2000); 	
		$('form').stop(true, false).animate({
				height : '200px'}, 2000)	

You just need to add in the stylesheet #form_wrap.hide:after, #form_wrap.hide:before {display:none;} and

#before {position:absolute;
		  width:530px;height: 316px;}
#after {position:absolute;
		width:530px;height: 260px; }

Looking forward to your comments, if you find this tutorial useful, please share and bookmark.