Skip to content

Instantly share code, notes, and snippets.

@shawnmclean
Created August 23, 2011 00:43
Show Gist options
  • Save shawnmclean/1164020 to your computer and use it in GitHub Desktop.
Save shawnmclean/1164020 to your computer and use it in GitHub Desktop.
Convert A canvas to image
<canvas id="MyCanvas" width="300" height="300">
</canvas>
<img id="MyImg"/>
<script>
function drawAndConvertStuff(canvas) {
var canvasContext = canvas.getContext('2d');
//draw a black box
canvasContext.fillRect(150, 25, 100, 100);
//create image object
var img = new Image();
img.src = '/Content/homer.jpg';
//wait until the image is loaded
img.onload = function() {
//draw the image
canvasContext.drawImage(img, 0, 0);
//convert it to image
var imgSrc = canvas.toDataURL("image/png");
$('#MyImg').attr('src', imgSrc);
};
}
//get the context. Non-jquery alternate: document.getElementById('MyCanvas').getContext('2d');
var can = $('#MyCanvas')[0];
drawAndConvertStuff(can);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment