jQuery img to canvas

Generate image to canvas mode

by Beben Koben

HTML

<center>
<img class="itc" src="http://1.bp.blogspot.com/-JrrsaBuKEys/T1EERkW6yXI/AAAAAAAAAmk/K7jwsKDsK5U/s400/alam.jpg" alt="" />
<img class="itc" src="http://4.bp.blogspot.com/-FQiQGjRCSLg/UVOvYzatLiI/AAAAAAAAMo0/ka7RXCOJe7w/s400/beben-koben.jpg" alt="" />
<img class="itc" src="http://3.bp.blogspot.com/-1Eu1hUJF180/TyacasYtwcI/AAAAAAAAAXw/N4Mbi7L51w8/s400/alam.jpg" alt="" />
</center>

CSS

body {background: #efefef}
canvas {
    border: none;
	margin: 5px auto;
	text-align: center;
	box-shadow: 1px 2px 3px #333;
}
.itc {
	width: 400px;
	height: 300px;
	margin: 10px;
	box-shadow: 1px 2px 5px #333;
}

JavaScript

/*
 * jQuery.imageToCanvas
 * ====================
 *
 * A jQuery plugin that turns an DOM image element into an HTML5 canvas while preserving the image data.
 *
 * http://github.com/schnalle/jQuery.imageToCanvas 
 */

(function($){$.fn.imageToCanvas=function(){var images=this.filter('IMG');var copyAttr='accesskey class contenteditable contextmenu dir draggable hidden id itemid itemprop itemref itemscope itemtype lang spellcheck style tabindex title'.split(' ');images.each(function(){var $img=$(this),img=this;var canvas=document.createElement('canvas'),$canvas=$(canvas),ctx=canvas.getContext('2d');var width=$img.width(),height=$img.height();$img.css({'width':null,'height':null});var cclass=$img.attr('class');$img.removeClass();var owidth=$img.width(),oheight=$img.height();for(var i=0;i<copyAttr.length;i++){var imgAttr=$img.attr(copyAttr[i]);if(imgAttr)$canvas.attr(copyAttr[i],imgAttr);}$canvas.attr('class',cclass);$canvas.attr('width',width);$canvas.attr('height',height);$canvas.css('width',width);$canvas.css('height',height);ctx.drawImage(this,0,0,owidth,oheight,0,0,width,height);$img.replaceWith($canvas);});return $;}})(jQuery);

$(document).ready(function () {
$('.itc').imageToCanvas();
});