Making charts in RaphaelJS that are 100% width?

前端 未结 3 867
忘掉有多难
忘掉有多难 2021-02-14 07:12

I have seen graphs in Flash & stuff that basically adapt nicely to whatever the size of the browser or flexible element they are inside of.... I\'m not really too well verse

相关标签:
3条回答
  • 2021-02-14 07:20

    This will get you a responsive SVG

    var w = 500, h=500;
    var paper = Raphael(w,h);
    paper.setViewBox(0,0,w,h,true);
    paper.setSize('100%', '100%');
    
    0 讨论(0)
  • 2021-02-14 07:31

    In raphaeljs, you can call .setSize on a Raphael object to update its size. To adapt to runtime changes in browser window size, you can respond to a window resize event. Using jQuery, you could do:

    // initialize Raphael object
    var w = $(window).width(), 
        h = $(window).height();
    
    var paper = Raphael($("#my_element").get(0), w,h);
    
    $(window).resize(function(){
         w = $(window).width();
         h = $(window).height();
         paper.setSize(w,h);
         redraw_element(); // code to handle re-drawing, if necessary
    });
    
    0 讨论(0)
  • 2021-02-14 07:45

    Normally you could set the width to %100 and define a viewBox within SVG. But, Raphael JS manually set a width and height directly on your SVG elements, which kills this technique.

    Bosh's answer is great, but it was distorting the aspect ratio for me. Had to tweak a few things to get it working correctly. Also, included some logic to maintain a maximum size.

    // Variables
    var width;
    var height;
    var maxWidth = 940;
    var maxHeight = 600;
    var widthPer;
    
    function setSize() {
        // Setup width
        width = window.innerWidth;
        if (width > maxWidth) width = maxWidth;
    
        // Setup height
        widthPer = width / maxWidth;
        height = widthPer * maxHeight;
    }
    var paper = Raphael(document.getElementById("infographic"), 940, 600);
    paper.setViewBox(0, 0, 940, 600, true);
    
    window.onresize = function(event) {
        setSize();
        paper.setSize(width,height);
        redraw_element();
    }
    
    0 讨论(0)
提交回复
热议问题