Svg-text-hit-test

I am trying to implement conflict detection for SVG text elements using client-side JavaScript. The test hit should check if any glyph of the text overlaps any glyph of the other text element. Since getBBox and getExtentOfChar are not exact, I need a special solution.

My first approach was to get the color of each coordinate / pixel of the element and do a hit check manually, but this does not work because it is impossible to get the color of the coordinate. To get pixel colors, you need an extra canvas β†’ a terrible workaround.

Now I'm thinking of converting text or glyphs to polygons for impact testing. Is it possible? Or does anyone have a different glyph-based testing approach?

Best wishes

+6
source share
2 answers

As for pixel-based testing - if you switch to HTML5 Canvas, this will be possible. Several projects provide an easy transition from SVG to Canvas, for example. fabric.js . See comparison table here .

As for the polygon-based approach, it is possible, but difficult. You can convert text or glyphs to polygons (paths) using some tool (for example, Inkscape text-to-path). And then there will be calculations. For a general solution, any text will require a lot of work. However, if the text does not change, then drawing the text manually using paths can be a quick and dirty solution.

0
source

You really enter the world of pain and cross browser issues. I ended up doing my own way of rendering fonts just to get the full length of the text reliable and consistent. I don’t even want to think about glyph bump.

One of the problems, for example, is that firefox (at least 3.6) and iirc also have some version of the opera that has some rounding error when scaling, so when you scale the parent element while holding the text, and scale the text using the inverse of this scale, the distance between the letters will be slightly different compared to any scale. (Since each letter should start with an even number or something like that, the problem can be solved by multiplying both the high-class and reduced scale by 10,000, but by a different story)

The performance impact using paths compared to text is unfortunately quite noticeable. If your canvas does any animated panning or zooming, you should switch to pure text elements during the animation and after statics, enable path rendering for accuracy.

Converting svg fonts in the path is very simple, it is plain text and using the same format as the path element. (be careful with embed font licenses!) Also consider the file size, as you cannot use fonts from the user system,)

+1
source

Source: https://habr.com/ru/post/894734/


All Articles