我正在使用 d3 库来创建 svg 图形。我遇到的问题是当我调整窗口大小时。整个图形的大小调整意味着文本(图例和轴)的大小也会调整,直到无法阅读。我需要它在调整大小时保持相同的大小。
我一直在网上搜索,找到了这个解决方案:
var resizeTracker;
// Counteracts all transforms applied above an element.
// Apply a translation to the element to have it remain at a local position
var unscale = function (el) {
var svg = el.ownerSVGElement;
var xf = el.scaleIndependentXForm;
if (!xf) {
// Keep a single transform matrix in the stack for fighting transformations
xf = el.scaleIndependentXForm = svg.createSVGTransform();
// Be sure to apply this transform after existing transforms (translate)
el.transform.baseVal.appendItem(xf);
}
var m = svg.getTransformToElement(el.parentNode);
m.e = m.f = 0; // Ignore (preserve) any translations done up to this point
xf.setMatrix(m);
};
[].forEach.call($("text"), unscale);
$(window).resize(function () {
if (resizeTracker) clearTimeout(resizeTracker);
resizeTracker = setTimeout(function () { [].forEach.call($("text"), unscale); }, 0);
});
并将其添加到我的代码中,但它不起作用。我调试了它并在这部分代码中:
var xf = el.scaleIndependentXForm;
它始终返回相同的矩阵:1 0 0 1 0 0,并且文本与其余 svg 元素一样不断调整大小,而不是保持静态。
请问有人可以帮我吗? 提前致谢。
最佳答案
同样的事情也发生在我身上,由 SnapSVG 生成的 SVG,直到我注意到 example page on which this does work在使用 el.ownerSVGElement.ownerSVGElement
而不是 el.ownerSVGElement
之前,将其“主”SVG 标签包装在另一个 SVG 标签中。
将我的 SVG 包装在“空”包装 SVG 中(注意样式 overflow:visible;
),我得到了更好的结果!
编辑:哦,等等。 Internet Explorer 仍然不满意。 Seems the author of the solution is aware...
关于javascript - 如何使用 Javascript 在 SVG 中绘制不可缩放的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32185332/