如何缩放内联SVG [英] How to scale inline SVG

查看:112
本文介绍了如何缩放内联SVG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在html中缩放内嵌SVG文档.我有这样的代码:

I want to scale inline SVG document in html. I have code like this:

var svg_width = svg.attr('width');
var svg_height = svg.attr('height');
function resize(width, height) {
    svg.attr('width', width).attr('height', height);
    var group = svg.find('#resize_group');
    if (!group.length) {
        group = svg.children().not('metadata, defs').wrapAll('<g/>').
            parent().attr('id', 'resize_group');
    }
    var matrix = svg[0].createSVGMatrix();
    //var matrix = group[0].getCTM();
    matrix.a = width/svg_width;
    matrix.d = width/svg_height;
    group.attr('transform', matrix.asString());
}

SVGMatrix.prototype.asString = function() {
    return 'matrix(' + this.a + ' ' + this.b + ' ' + this.c + ' ' + this.d +
           ' ' + this.e + ' ' + this.f + ')';
};

注意:我需要转换svg中的元素,因为否则图像将被修剪.

NOTE: I need to transform the elements inside svg because otherwise the image is trimmed.

但是当我调用resize函数时,整个svg消失了.我将svg保存到文件中,并在Inkscape中打开,它看起来很正常(已缩放).为什么svg消失了? (我在Firefox,Chrome和Opera上进行了测试)

but when I call resize function whole svg disappear. I've save svg to file and open it in Inkscape and it look normal (it's scaled). Why the svg disappear? (I tested on Firefox, Chrome and Opera)

推荐答案

我发现了快速破解,将svg替换为svg的文本以强制重绘.

I found quick hack, to replace svg with text of the svg to force redraw.

$.fn.xml = function() {
    return (new XMLSerializer()).serializeToString(this[0]);
};

$.fn.SVGRedraw = function() {
    return $(this.xml()).replaceAll(this);
};

这篇关于如何缩放内联SVG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆