2010-10-18 23 views

回答

7

在raphaeljs中,您可以調用Raphael對象上的.setSize來更新其大小。爲了適應瀏覽器窗口大小的運行時更改,可以響應窗口大小調整事件。使用jQuery,您可以:

 
// 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

使用'paper.setSize'農作物我SVG而無需縮放;我將如何擴展,而不是僅僅裁剪? – supertrue 2012-08-20 04:54:09

0

通常,您可以將寬度設置爲%100並在SVG中定義一個viewBox。但是,Raphael JS會直接在SVG元素上設置寬度和高度,這會殺死這種技術。

波什的回答非常好,但它對我來說扭曲了長寬比。必須調整一些東西才能正常工作。此外,還包括一些邏輯來保持最大尺寸。

// 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(); 
} 
3

這將讓你一個負責任的SVG

var w = 500, h=500; 
var paper = Raphael(w,h); 
paper.setViewBox(0,0,w,h,true); 
paper.setSize('100%', '100%'); 
+0

這對我有用。當我縮小窗口的時候,SVG縮小了,但並沒有擴大;它的大小在最初的寬度和高度被封頂。另外,我僅爲寬度指定了「100%」。 – 2014-09-09 14:27:56

+0

編輯:100%的高度是必要的,否則高度不會隨着比例變化而變化。這相當於CSS中的'height:auto'。 – 2014-09-09 17:34:32