sharp icon indicating copy to clipboard operation
sharp copied to clipboard

SVG: support for CSS calc()

Open JesseZeng2 opened this issue 4 years ago • 6 comments

Hello, I want to output a line graph SVG to a png using Sharp. The axis and legends are on top of the padding space of the SVG as overflow, shown in the picture below.

graph1

But it seems the padding area does not get included into the output png file.

output

I used the following code to create the output:

const element = renderToString(svg);
sharp(Buffer.from(element))
.png()
.toFile("output.png", Object);

Here is also a JSFiddle with the SVG: https://jsfiddle.net/Lefsqo3j/14/

Is there a way for the padding area to be captured in the output png together with the graph? Thank you.

JesseZeng2 avatar Jan 24 '22 02:01 JesseZeng2

Hi, it looks like the outer svg element has no sizing information, so you'll probably want to provide at least a viewBox. To allow room for the padding you'll also need to use negative values for the top/left, something like <svg viewBox="-40 -24 300 100" ...

lovell avatar Jan 24 '22 11:01 lovell

Hi @lovell,

Unfortunately this will not work if you go to the fiddle and add these properties to the viewbox on the parent you'll notice the box model now starts to overflow.

The padding is there to allow fixed pixel space for the axis and legend which aren't responsive, the padding pushes the "lines" right 40px to make room for the axis without triggering overflow.

If you don't use padding the only way to move the lines right 40px (to make room for the axis) would be to use x="40px" which would then trigger overflow on the right side of the graph. This can be fixed by also putting width="calc(100% - 40px)" which is valid SVG syntax however these calc values seem to break sharp.

Is there any way to move the lines 40px to the right and shrink its width by 40px using syntax compatible with the Sharp library? If not would it be hard to add support for "calc" in width/height attributes

JesseZeng2 avatar Feb 03 '22 21:02 JesseZeng2

Thanks for the update. SVG rendering in sharp/libvips is dependent upon librsvg, so may I suggest your next move is try to experiment with the rsvg-convert command line tool provided by librsvg.

lovell avatar Feb 03 '22 22:02 lovell

@JesseZeng2 Were you able to make any progress by experimenting with rsvg-convert?

lovell avatar Mar 31 '22 13:03 lovell

Hi @lovell, I've raised an issue in librsvg, however I have not made any progress otherwise.

JesseZeng2 avatar Apr 01 '22 03:04 JesseZeng2

Thanks for the update, and thank you for reporting this upstream.

lovell avatar Apr 01 '22 08:04 lovell