Canvas image download

for: https://stackoverflow.com/questions/10673122/how-to-save-canvas-as-an-image-with-canvas-todataurl

by vijayweb

HTML

<canvas width="100" height="100"></canvas>
<div id="hello"><a href="#" download="image.png">download image</a></div>

CSS

canvas {
  box-shadow: 0 0 16px rgba(0,0,0,0.1);
}

JavaScript

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const anchor = document.querySelector('a');
const rand = i=>Math.random()*i<<0



var img = canvas.toDataURL();

$('#hello').append('<img src="'+img+'">');

function drawOntoCanvas(){
  const size = 100;
  context.fillStyle = 'rgba(255,0,0,0.4)';
  let i = 10;
  while (i--) {
    context.fillRect(rand(size),rand(size),rand(size),rand(size));
  }
}