Making charts in RaphaelJS that are 100% width?

偶尔善良 提交于 2019-12-03 12:55:07

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
});

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%');

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();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!