Msc Final Project

Download your canvas as an image (canvas)

As my website badly needs an online texture generator, downloading canvas becomes a must…

The core of code below is “toDataURL()”.


<html>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<head>

window.onload = function() {
  draw();
  var dlButton = document.getElementById("downloadImageBtn");
  bindButtonEvent(dlButton, "click", saveAsLocalImage);
};
function draw(){
  var canvas = document.getElementById("thecanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
  ctx.fillRect(25,25,100,100);
  ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
  ctx.fillRect(58, 74, 125, 100);
}
function bindButtonEvent(element, type, handler){
  if(element.addEventListener) {
    element.addEventListener(type, handler, false);
  } else {
    element.attachEvent('on'+type, handler);
  }
}
function saveAsLocalImage () {
  var myCanvas = document.getElementById("thecanvas");
  var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
  window.location.href=image;
}

</head>
<body>
Download Image
</body> </html>  

Reference site: http://www.jb51.net/html5/83401.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s