2013-08-09 3 views
2

У меня есть страница, где есть 2 диаграммы пирога, сгенерированные с использованием gRaphael. Я также использую пару плагинов для создания .png из этих документов. Моя проблема заключается в том, что независимо от того, что она всегда использует первую бумагу, даже если я использую правильную ссылку (т. Е. Изображение всегда является первым графиком, даже если я делаю это для второго). Вот мой код:gRaphael: проблема с доступом к многократным бумагам

//make sure this element exists before creating pie chart 
     if(document.getElementById("hour_pie")) 
     { 
      //extract labels into gRaphael appropriate format 
      totalArry=new Array(); 
      for(var key in hours_total) 
      { 
       totalArry.push(hours_total[key]); 
      } 

      //create canvas 
      var hourPaper = Raphael("hour_pie"); 
      //create pie chart 
      var hourPie=hourPaper.piechart(
       hourPaper.width/2, // pie center x coordinate 
       hourPaper.height/2, // pie center y coordinate 
       200, // pie radius 
       totalArry, // values 
       { 
        legend: hours_pie_labels 
       } 
      ); 


       // hover animation 
       hourPie.hover(function() { 
        this.sector.stop(); 
        this.sector.scale(1.1, 1.1, this.cx, this.cy); 

        if (this.label) { 
         this.label[0].stop(); 
         this.label[0].attr({ r: 7.5 }); 
         this.label[1].attr({ "font-weight": 800 }); 
        } 
       }, function() { 
        this.sector.animate({ transform: 's1 1 ' + this.cx + ' ' + this.cy }, 500, "bounce"); 

        if (this.label) { 
         this.label[0].animate({ r: 5 }, 500, "bounce"); 
         this.label[1].attr({ "font-weight": 400 }); 
        } 
       }); 
      //on click of this img, convert canvas to .png and prompt download  
      $('.hour_download').click(function() 
      { 
       // turn svg into PNG 
       SVGtoPNG(hourPaper.toSVG(), "hourPieGraph"); 
      }); 
     } 
     if(document.getElementById("explosive_pie")) 
     { 

      //extract labels into gRaphael appropriate format 
      totalArry=new Array(); 
      for(var key in explosive_totals) 
      { 
       totalArry.push(explosive_totals[key]); 
      } 
      //create canvas 
      var explosivePaper = Raphael("explosive_pie"); 
      //create pie chart 
      var explosivePie=explosivePaper.piechart(
       explosivePaper.width/2, // pie center x coordinate 
       explosivePaper.height/2, // pie center y coordinate 
       200, // pie radius 
       totalArry, // values 
       { 
        legend: explosive_pie_labels 
       } 
      ); 


       // hover animation 
       explosivePie.hover(function() { 
        this.sector.stop(); 
        this.sector.scale(1.1, 1.1, this.cx, this.cy); 

        if (this.label) { 
         this.label[0].stop(); 
         this.label[0].attr({ r: 7.5 }); 
         this.label[1].attr({ "font-weight": 800 }); 
        } 
       }, function() { 
        this.sector.animate({ transform: 's1 1 ' + this.cx + ' ' + this.cy }, 500, "bounce"); 

        if (this.label) { 
         this.label[0].animate({ r: 5 }, 500, "bounce"); 
         this.label[1].attr({ "font-weight": 400 }); 
        } 
       }); 

      //on click of this img, convert canvas to .png and prompt download 
      $('.explosive_download').click(function() 
      { 
       // turn svg into PNG 
       SVGtoPNG(explosivePaper.toSVG(), "explosivePieGraph"); 
      }); 
     } 

и HTML:

<div id="hour_pie" class="pie_chart"></div><img class="download_image hour_download" title="Download this graph" src="/images/download_small.png"></img> 

<div id="explosive_pie" class="pie_chart" ></div><img class="download_image explosive_download" title="Download this graph" src="/images/download_small.png"></img> 
    <style type="text/css"> 
    .pie_chart 
    { 
     width:1000px; 
     height:450px; 
    } 
    .download_image 
    { 
     display: block; 
     margin-left: auto; 
     margin-right: auto; 
    } 


</style> 
+0

Можем ли мы увидеть вашу разметку HTML? У меня были странные проблемы с несколькими документами, где у разделов хоста не было никаких предопределенных стилей или размеров. –

+0

@KevinNielsen HTML был добавлен –

+2

Спасибо, но похоже, что мой запрос был неверно направлен. То, что я должен * на самом деле * попросить посмотреть, это библиотеки, которые вы используете для преобразования в PNG - в частности, источник SVGtoPNG и метод paper.ToSVG. Извините =/ –

ответ

1

Вопрос у меня был был результат, как я извлеченного полотно из XML. Как я понял, мультипликационные холсты хранятся в массиве, и они не возвращаются из документа отдельно (что имеет смысл в ретроспективе). Поэтому, учитывая мою реализацию, мне нужно знать индекс холста, который я хочу преобразовать в .png. Это было в функции SVGtoPNG. Более подробно относительно строки var svgElement = document.body.getElementsByTagName ("svg") [1]; 0 мой первый холст, 1 второй холст и т. Д.

function SVGtoPNG(xml, name) { 

    try 
    { 
     //add canvas into body  
     var canvas = document.createElement('canvas'); 
     canvas.id = "myCanvas"; 
     document.body.appendChild(canvas); 

     //default is 'xml' (used for IE8) 
     var finalSvg=xml; 

     // IE8 is special and a pain in the ass 
     if(BrowserDetect.browser==="Explorer" && BrowserDetect.version===8) 
     { 
     FlashCanvas.initElement(canvas); 
     } 
     else 
     { 
     //serialize svg 
     var svgElement = document.body.getElementsByTagName("svg")[1]; 
     var svgXml = (new XMLSerializer()).serializeToString(svgElement); 
     finalSvg = svgXml.FixForRaphael(); 
     } 
Смежные вопросы