Skip to content

Instantly share code, notes, and snippets.

@simonkim
Last active December 20, 2015 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simonkim/6109951 to your computer and use it in GitHub Desktop.
Save simonkim/6109951 to your computer and use it in GitHub Desktop.
Loading an image dynamically and drawing in <canvas> without a static <img> tag in JavaScript
/* Application of HTML5 Canvas Image Tutorial at http://www.html5canvastutorials.com/tutorials/html5-canvas-images/ */
function sshow_load_img1(src, loaded) {
/* Loading image dynamically using jQuery */
var img = $("<img />").attr('src', src )
.load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
/* img is a jQuery object. Take DOM Element object out of it using .get(index) */
if (loaded) loaded(img.get(0));
}
});
}
function sshow_load_img2(src, loaded) {
/* Possible to document.createElement('canvas').getContext('2D').drawImage( img ) */
var img = new Image();
img.onload = function() {
if ( loaded ) loaded (img);
};
img.src = src;
}
/* Prepare Canvas, load image and draw */
var canvas = document.createElement('canvas'),
canvasContext = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 320;
$('#slideshow').append(canvas);
sshow_load_img1( 'images/1.jpg', function( img ) { canvasContext.drawImage( img, 0, 0 ) } );
/* or */
sshow_load_img2( 'images/1.jpg', function( img ) { canvasContext.drawImage( img, 0, 0 ) } );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment