svgdotjs / svg.js

The lightweight library for manipulating and animating SVG
https://svgjs.dev
Other
11.04k stars 1.08k forks source link

Export SVG with export modifier round() kills all polygones/polylines points (3.0.16), on master it does not round #1153

Closed jbiermann closed 1 year ago

jbiermann commented 3 years ago

Bug report

The round export modifier function kills arbitrary attributes (3.0.16) or polygon/polyline points (3.0.16) on master it does not work on polygone/polyline shapes. I am referencing to the round example from the documentation.

Fiddle

See this fiddle. Here I load an existing SVG shape from DOM, do some manipulation with it and export it a) svg() and b with svg(function(node) { ...} ) with the round export modifier. I set the output to the textarea box.

Explanation

That the round export modifier function rounds the points to the desired accuracy on all shape types and keeps every other attribute (e.g. ID) as they have been set before.

None, the output of the function is wrong.

Fuzzyma commented 3 years ago

round takes a second parameter map which defines which attributes should be rounded. By default it rounds nothing. However, the round method has no concept of rounding a delimited string like the points attribute has. It just converts every string to number and rounds it. If you want to round points, you need to do it yourself:

var codeRounded = item.svg(function(node) {
  const round = (n) => Math.round(n * 1000)/1000
  if (node.type.startsWith('poly')) {
    node.attr('points', node.array().map((p) => p.map(round)))
  }
});

https://jsfiddle.net/Fuzzy/q3agtukr/

jbiermann commented 3 years ago

thank you, that does work. I did not note that it does not treat delimited strings. The accidentality deleting of points / attributes of the build in round function is already fixed in the master trunk.

Maybe your comment is a good candidate for adding this to the documentation?

Fuzzyma commented 3 years ago

Yeah maybe :D