如何显示/下载RaphaelJs画布作为图像(png / gif)?

时间:2013-01-04 21:51:22

标签: javascript png raphael image

如何让用户下载使用RaphaelJs生成的图像?我会优先将它作为<img>显示在HTML上,以便他们可以右键单击图像以将其保存到桌面。

1 个答案:

答案 0 :(得分:13)

以下是将RaphelJs转换为图像所需的简单示例

所需的libarys是:

-

<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,你有你的形象!我希望这可以很好地用于某人!