An SVG Round-trip

Yesterday, I was given a task to correct the logo images in DEV instance for the text based logos. We were rendering text converted into SVG and then loaded as an image in the header.

The rendered image was clipped from the right edge and was not rendering the logo correctly. Seemed easy fix so I just got it assigned to myself. and my journey started.

Attempt 1: removing the dynamic width from the SVG.

This immediately fixed the clipping issue but now the generated image has white-space at the end and taking more space in the header.

Attempt 2: increasing the width by a fixed number of pixels.

This solved for the problem at hand, but for other texts that were working, are now broken and has extra space at the end.

Attempt 3: generating, rendering and then cropping the image

Too complex and heavy operation, downvoted.

Attempt 4: Creating a viewBox of a certain size and aligning using the preserveAspectRatio and text-length attributes.

Did not work well for me. Although it can solve the issue.

Attempt 5: Scaling to 90% so that it can fit.

Scaled down to 90% using ‘g’ tag, but again same issue more white-space at the end and smaller fonts.

Attempt 6: SVG inside SVG

It worked but was ugly, needed more changes.

Attempt 7: Get a break, walk around the building and a cup of hot coffee.

I was just staring at the code at this moment, had already restored my changes multiple times and I was at the same place where I started. Soon i realised that the clipping is happening because the calculation of the required width could be buggy.

I checked the code, we were calculating the required width using canvas API by setting the font and then measuring the width for the text rendering.

The font was “Some font”, but in the svg text element had a font family “Some font Bold, Some font”. I updated the same font family in the context and now it started working as expected. It was a font setting issue.

I took many hours to fix this very tiny issue but learnt a lot of SVG images, how they are created, how it works and how we can leverage to scale text. This was a good refresher for me but the pull request only contained one line and my boss might not be happy that I took that much time to solve it.

Links:

https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/viewBox

https://developer.mozilla.org/en-US/docs/Web/SVG/Reference

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText

https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Element/g

Leave a Reply

Your email address will not be published. Required fields are marked *