Making charts in RaphaelJS that are 100% width?

前端 未结 3 865
忘掉有多难
忘掉有多难 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: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();
    }
    

提交回复
热议问题