geostyler / geostyler-legend

Small library to render map legends with OpenLayers and d3
BSD 2-Clause "Simplified" License
12 stars 9 forks source link

Add a PNG output to LegendRenderer #393

Closed jahow closed 1 year ago

jahow commented 2 years ago

This PR refactors the LegendRenderer class to externalize all "rendering" logic (i.e. using D3 and SVG) to a separate SvgOutput class with atomic operations (add image, add label, etc.).

Then, another PngOutput class is added and LegendRenderer can essentially use both interchangeably. Also added a renderAsImage method to the LegendRenderer API in order to obtain an image without providing a container, useful when the legend is intended to be downloaded instead of being added to the DOM.

To use PNG output:

const renderer = new LegendRenderer({
  // ...
});
renderer.render(target, 'png');

// or
const canvas = await renderer.renderAsImage('png'); // returns a HTMLCanvasElement

The important part is that the default behavior of LegendRenderer (generating an SVG and appending it) is almost entirely unchanged. The only difference is about the root svg namespace which is sometimes added when it was not before (see commits).

Caveat: labels are not shortened in the PNG output. This will need a bit more refactoring so I thought I'd leave that for later.

Remaining to do:

Also I think it would be nice to set up some wider regression tests so that it's easier to add more features, e.g. automatic width adjustment, more options to customize layout, etc.!

Fixes #390

jansule commented 2 years ago

From a first glance, this looks really good! Thanks @jahow

Could you let us know, when this is ready for review?

jahow commented 2 years ago

Sure, hopefully in the coming days!

jahow commented 1 year ago

Making slow progress on this but I haven't forgotten :nerd_face:

jahow commented 1 year ago

@jansule the test coverage is now pretty good, this is ready for review.

I couldn't make a test app yet but this is in my plans for later. At least this PR should keep the default behaviour unchanged and not break anything!

jahow commented 1 year ago

@jansule this is good to merge!