Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/download RaphaelJs canvas as an image(png/gif)? [closed]

How can i make users download the image generated with RaphaelJs? I would prefere if it was displayed on the HTML as an <img> so they could rightclick the image to save it to the desktop.

like image 969
Sultanen Avatar asked Jan 31 '26 18:01

Sultanen


1 Answers

Here is a simple example of whats needed to convert RaphelJs to an image

The libarys needed are:

  • RaphaelJs - http://raphaeljs.com/
  • Raphel.Export - https://github.com/ElbertF/Raphael.Export
  • canvg - http://code.google.com/p/canvg/

-

<script type="text/javascript" src="raphaeljs.js"></script>        
<script type="text/javascript" src="raphael.export.js"></script>        
<script type="text/javascript" src="canvg.js"></script>

   <script>

   window.onload = function(){

       //Start with a simple raphaelJs drawing
       var paper = new Raphael(document.getElementById('raphaelDiv'), 200, 200);
       var circle = paper.circle(50, 40, 10);
       circle.attr("fill", "#f00");
       circle.attr("stroke", "#fff");
       var circle2 = paper.circle(70, 60, 50);

       //Use raphael.export to fetch the SVG from the paper
       var svg = paper.toSVG();

       //Use canvg to draw the SVG onto the empty canvas
       canvg(document.getElementById('myCanvas'), svg);


       //I had to use setTimeout to wait for the canvas to fully load before setting the img.src,
       //will probably not be needed for a simple drawing like this but i ended up with a blank image
       setTimeout(function() {
           //fetch the dataURL from the canvas and set it as src on the image
           var dataURL = document.getElementById('myCanvas').toDataURL("image/png");
           document.getElementById('myImg').src = dataURL;
       }, 100);
   }

</script>

<!--The containers below are set to be invisible, we need them for the 
    conversion but we dont need to se them-->
<div id="raphaelDiv" style="display:none;"></div>
<canvas id="myCanvas" style="display:none;"></canvas>


<img id="myImg" src="">

Wola, you got your image! I hope this could be to good use for someone!

like image 188
Sultanen Avatar answered Feb 02 '26 08:02

Sultanen