Skip to content

Instantly share code, notes, and snippets.

@mlaug
Created April 7, 2012 19:19
Show Gist options
  • Save mlaug/2331490 to your computer and use it in GitHub Desktop.
Save mlaug/2331490 to your computer and use it in GitHub Desktop.
Async Image Loader
<!DOCTYPE html>
<html>
<head>
<title>Image Loader</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://remysharp.com/downloads/jquery.inview.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.canvas-image-loader').bind('inview',function(event, visible){
var _this = this;
var $this = $(this);
if ( visible == true && $this.data('drawed') !== true){
//create image from url
var img = new Image();
img.src = $this.attr('data-url');
img.onload = function(){
//get canvas
var canvas = document.getElementById(_this.id);
//resize the canvas to fit the image
canvas.width = img.width;
canvas.height = img.height;
//get 2d context and add image
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
//mark as drawed and remove handler to save perfomance
$this.data('drawed', true);
$this.unbind('inview');
}
}
});
//trigger scroll event on first page view, so that all elements, which are already in view will be displayed
$(window).scroll();
});
</script>
</head>
<body>
<canvas
class="canvas-image-loader"
id="canvas-image-loader-1"
data-url="http://www.fabula-filmpuppen.de/Samson_und_Bibo_Hangematte.jpg">
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment