gpt4 book ai didi

javascript - Raphael 路径调整大小并相对于容器移动

转载 作者:行者123 更新时间:2023-11-30 10:22:02 24 4
gpt4 key购买 nike

我正在尝试缩放/移动使用 Raphael api 创建的 SVG 路径。我希望路径能够整齐地放入容器中,无论容器的大小如何。我已经搜索了引用资料和网络,但我仍在努力让它发挥作用。

如果有人能告诉我为什么这不起作用,我会很高兴。

这个 fiddle 向您展示了我在做什么:http://jsfiddle.net/tolund/3XPxL/5/

JavaScript:

var draw = function(size) {
var $container = $("#container").empty();
$container.css("height",size+"px").css("width",size+"px");

var paper = Raphael("container");

var pathStr = "M11.166,23.963L22.359,17.5c1.43-0.824,1.43-2.175,"+
"0-3L11.166,8.037c-1.429-0.826-2.598-0.15-2.598,"+
"1.5v12.926C8.568,24.113,9.737,24.789,11.166,23.963z";

// set the viewbox to same size as container
paper.setViewBox(0, 0, $container.width(), $container.height(), true);

// create the path
var path = paper.path(pathStr)
.attr({ fill: "#000", "stroke-width": 0, "stroke-linejoin": "round", opacity: 1 });

// get the path outline box (may be different size than view box.
var box = path.getBBox();

// move the path as much to the top/left as possible within container
path.transform("t" + 0 + "," + 0);

// get the width/height based on path box relative to paper (same size as container)
var w = (paper.width) / box.width;
var h = (paper.height) / box.height;

// scale the path to the container (use "..." to compound transforms)
path.transform('...S' + w + ',' + h + ',0,0');
}

$(function() {
var currentSize = 30;
draw(currentSize);

$("#smaller").click(function(){
currentSize = currentSize < 10 ? currentSize : currentSize * 0.5;
draw(currentSize);
});
$("#bigger").click(function(){
currentSize = 300 < currentSize ? currentSize : currentSize * 2;
draw(currentSize);
});
});

HTML:

<button id="smaller">-</button>
<button id="bigger">+</button>

<div id="container" style="border: 1px #ddd solid; margin: 30px">

</div>

谢谢,托吉尔。

最佳答案

我认为您的问题是对 View 框的用途存在根本性的误解。在您的代码中,您试图设置 svg 元素的视框,使其与屏幕的坐标空间匹配,然后转换路径以匹配该坐标空间。没有技术原因您不能这样做,但它确实有效地从“可缩放矢量图形”中去除了“可缩放”。 viewbox 的全部意义在于使矢量坐标空间和屏幕之间的平移相对。

那么,解决您的问题的最佳方法不是转换路径以匹配 SVG 元素,而是使用 View 框让 SVG 的内在可伸缩性为您完成此操作。

首先要做的事情是:创建您的路径,以便我们有一个可以使用的对象。此时我们不关心 View 框是什么。

var pathStr = "...";  // The content of the path and its coordinates are completely immaterial

var path = paper.path(pathStr)
.attr({ fill: "#000", "stroke-width": 0, "stroke-linejoin": "round", opacity: 1 });

现在我们需要做的就是使用 View 框将 SVG“聚焦”在我们感兴趣的坐标空间上。

var box = path.getBBox();    
var margin = Math.max( box.width, box.height ) * 0.1; // because white space always looks nice ;-)
paper.setViewBox(box.x - margin, box.y - margin, box.width + margin * 2, box.height + margin * 2);

就是这样。 SVG(无论大小)将从 View 框中指定的内部坐标转换为其在屏幕上的物理坐标。

这是你的 fiddle 的 fork proof-of-concept .

关于javascript - Raphael 路径调整大小并相对于容器移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21140786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com