The problem is that you do not wait for the original image element to load. If you change it a little, it works fine:
$(function() { var canvas = document.createElement('canvas'), canvasExists = !!(canvas.getContext && canvas.getContext('2d')), oImage = $('img')[0]; if (canvasExists) { var context = canvas.getContext('2d'), img = new Image(); img.onload = function() { canvas.height = img.height; canvas.width = img.width; $(oImage).replaceWith(canvas); context.drawImage(oImage, 0, 0); } img.src = oImage.src; } else {
source share