捕获SVG并重新缩放为微型

Capture SVG and rescale to miniature

本文关键字:缩放 微型 SVG 新缩放 捕获      更新时间:2023-09-26

我有一个用Raphael.js编写的小应用程序,它使用SVG绘制节点网络并根据给定的选择重新排列它。

我需要能够做的是捕获我绘制的svg图片并将其显示在屏幕底部的"迷你地图"类型的显示器上。因为我不知道画布会是什么样子,当我捕获它,我想知道是否有可能只是捕获它作为一个位图或类似的东西?

把一个快速的小提琴放在一起,以显示接近我的意思:

http://jsfiddle.net/WNnCH/1/

有没有办法做到:SVG.copy ?还是SVG.img ?(我确定没有,但你知道我的意思吗?)

我已经研究了如何捕获整个SVG并调整它的大小(这比我认为我想写的或必要的代码更多),甚至复制整个SVG,但我不知道是否有可能捕获SVG作为图像并将其缩小到我需要的大小。

小地图不需要是SVG,它可以只是一个图像,因为它基本上只是一个历史的屏幕看起来像一个先前的动作。

谢谢你的建议!

您可以通过创建指向第一个主SVG的不同缩放SVG来轻松地制作主SVG的缩略图。

<div id="main">
    <svg id="mainsvg" viewBox="0 0 1000 1000">
        <rect x="100" y="100" width="500" height="500" fill="green"
              transform="rotate(10,350,350)"/>
        <rect x="400" y="400" width="500" height="500" fill="orange"
              transform="rotate(-10,650,650)"/>
    </svg>
</div>

<div id="thumb">
    <svg xmlns:xlink="http://www.w3.org/1999/xlink">
        <use xlink:href="#mainsvg" />
    </svg>
</div>

SVG的大小由CSS决定:

#main {
    width: 400px;
    height: 400px;
}
#thumb {
    width: 80px;
    height: 80px;
}

你可以对主SVG做任何你想做的事情,拇指会反映所有的变化。

Demo

有一种方法可以做到这一点,只使用Raphael,用你的小地图元素创建一个集合,然后克隆它。然而,如果你想让小地图成为一个独立的实体/文件,这就更棘手了。我从这个答案中借用了一些代码来克隆你的地图到一个新的论文,它工作得很好(jsfiddle)

(function (R) {
    var cloneSet; // to cache set cloning function for optimisation
    /**
     * Clones Raphael element from one paper to another
     *     
     * @param {Paper} targetPaper is the paper to which this element 
     * has to be cloned
     *
     * @return RaphaelElement
     */
    R.el.cloneToPaper = function (targetPaper) {
        return (!this.removed &&
            targetPaper[this.type]().attr(this.attr()));
    };
    /**
     * Clones Raphael Set from one paper to another
     *     
     * @param {Paper} targetPaper is the paper to which this element 
     * has to be cloned
     *
     * @return RaphaelSet
     */
    R.st.cloneToPaper = function (targetPaper) {
        targetPaper.setStart();
        this.forEach(cloneSet || (cloneSet = function (el) {
            el.cloneToPaper(targetPaper);
        }));
        return targetPaper.setFinish();
    };
}(Raphael));
var paper = Raphael(30, 30, 200, 200);
var circle = paper.circle(30, 30, 30);
circle.attr("fill", "#ccc");
var circle1 = paper.circle(70, 70, 30);
circle1.attr("fill", "#ccc");
var circle2 = paper.circle(110, 30, 30);
circle2.attr("fill", "#ccc");
var circle3 = paper.circle(30, 110, 30);
circle3.attr("fill", "#ccc");
var circle4 = paper.circle(110, 110, 30);
circle4.attr("fill", "#ccc");
var s = paper.set();
s.push(circle, circle1, circle2, circle3, circle4);
var minipaper = Raphael(document.getElementById("minimap").getElementsByTagName("div")[1], 140, 140);
var miniset = s.cloneToPaper(minipaper);
miniset.transform("s0.5,0.5,55,55"); // scale by 0.5 around (55,55)