2013年2月13日水曜日

JavaScriptでSVGを使うまとめ

細々とまとめてみる。
何か表示が崩れるけどまあいいや。



SVGを動的に配置する

下記で100x100サイズのSVGを、IDがaaaaaのエレメントに追加できる。

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute("width" , 100);
svg.setAttribute("height", 100);
svg.setAttribute("viewBox", "0 0 100 100");
document.getElementById("aaaaa").appendChild(svg);



動的に図形とか配置する

矩形の場合は下記のように。

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("width" , 50);
rect.setAttribute("height", 50);
svg.appendChild(rect);


画像の場合は下記のように。

var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
img.setAttributeNS(null, "width" , 50);
img.setAttributeNS(null, "height", 50);
img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", (画像のURL));
svg.appendChild(img);


ここらで注意なのが、属性の指定を「getAttribute」ではなく「getAttributeNS」を使うこと。
これを使わないと、値は設定できても反映されない。
上記矩形は使わなくても行けたっぽいのでgetAttributeのままにしてます。



矩形とかのサイズを取得する

getBBoxを使う。
例えば、上記で作った矩形のサイズを取るときは、

var s = rect.getBBox();

みたいにすれば取れる。
取れる値は、x, y, width, heightの4つ。
それぞれ左上原点でx座標、y座標、幅、高さ。

ただし、svgを非表示にしていたりすると取れないので注意。

また、ChromeとSafariで取れる値が違ったので注意。
特に、<path>で図形を書くと発生する。
例えば<path d="M100,100L200,200.....">というのがあったとする。
これは、x=100,y=100の位置からx=200,y=200の位置に線を引いて....という記述。
これに対し、それぞれでgetBBoxすると、
片方はx=100,y=100,,,と取れるのに、
一方はx=0,y=0,,,と、位置が変に取れてしまう。
バグかどうかは不明だが、しょうがないので<path d="M0,0M100,100L200,200....">
とすれば、とりあえずは同じ値を取得することができるようになる。



SVG要素まるごとテキストとして出力する

SVGでエディタとか作って、それで編集したデータをどこかに保存したいときとかに。

var t = (new XMLSerializer()).serializeToString(svg);



SVGのデータをCanvasに出力する

canvgというライブラリを使うと便利。
画像や複雑なパスもうまいこと処理してくれるよう。


http://code.google.com/p/canvg


使い方は下記のように。
canvgで指定するsvgはStringでないといけないみたいなので、
上記「SVG要素まるごとテキストとして出力する」で出力したデータをぶち込めば良い。
画像とかあると、読み込み完了のタイミングが非同期になるので、
callbackを受けてから処理を続けると良い。


// canvasを動的につくってみる
var cvs = document.createElement("canvas");
cvs.setAttribute("width" , 100);
cvs.setAttribute("height", 100);

// svgはテキストで
var svgTxt = "<svg .....>....</svg>";

// svgをcanvasに描画
canvg(
    cvs,                            // 対象canvas
    svgTxt,                         // 描画するsvg
    {
        ignoreMouse      : true,    // マウスイベント無視
        ignoreAnimation  : true,    // アニメーション無視
        ignoreDimensions : true,    // canvasサイズをsvgに合わせない
        ignoreClear      : true,    // svg描画時にcanvasをクリアしない
        offsetX          : 0,       // svg描画位置
        offsetY          : 0,       // svg描画位置
        scaleWidth       : 100,     // svg描画サイズ
        scaleHeight      : 100,     // svg描画サイズ
        renderCallback   : function(){
            // 例:canvas描画完了時に画像を変数に出力
            var img = cvs.toDataURL("image/png");
        }
    }
);


注意なのが、画像を別ドメインなどから読み込んでいたりすると、
上記例にあるtoDataURLが失敗する。

また、上記引数の「scaleWidth」とかは計算が特殊みたいなので、
詳しく知りたい方は詳細は本家ドキュメントなどを参考に。


SVGをIllustratorとかで読み込む

一応、IllustratorでSVG読み込みはできるが、崩れてしまって使いものにならない。
そこで、一度EPS変換して読み込ませると良い。

そのソフトのおすすめはInkscape(http://inkscape.org)。
Windowsの他、Linux版もある。

コマンドラインでSVGを渡してEPS変換もできるので、
例えばPHPとかから呼び出せば簡単にEPS出力できる。

コマンドについては下記を参考に。

http://inkscape.paix.jp/manual/cmdline-usage.html




1 件のコメント:

  1. In this fashion my pal Wesley Virgin's report begins with this shocking and controversial video.

    You see, Wesley was in the military-and shortly after leaving-he revealed hidden, "MIND CONTROL" tactics that the CIA and others used to get whatever they want.

    These are the exact same SECRETS many celebrities (notably those who "come out of nothing") and elite business people used to become rich and famous.

    You've heard that you only use 10% of your brain.

    Mostly, that's because most of your brainpower is UNTAPPED.

    Perhaps that conversation has even occurred INSIDE your own head... as it did in my good friend Wesley Virgin's head around 7 years back, while riding an unlicensed, beat-up garbage bucket of a car without a driver's license and with $3.20 in his bank account.

    "I'm so fed up with living paycheck to paycheck! When will I finally succeed?"

    You've been a part of those those questions, am I right?

    Your very own success story is waiting to start. You just need to take a leap of faith in YOURSELF.

    Take Action Now!

    返信削除