JavaScript Canvas - Text, Typography & SVG |
Written by Ian Elliot | |||
Monday, 04 November 2019 | |||
Page 2 of 2
SVG Text on CanvasThis is an advanced topic that uses techniques from later in the book. Canvas text is fine for basic tasks but it lacks the typographical control needed for more advanced tasks. SVG text, on the other hand, has all of the characteristics of CSS text and is much more sophisticated. For example, you can adjust the individual positions of characters, change letter spacing, change word spacing, select kerning and so on. To find out how to do these things, all you need to do is to look up the CSS attributes needed to style text. This is one function that will render SVG text: async function text(ctx,x,y, text, style) { var svg = '<svg xmlns="http://www.w3.org/2000/svg" height="80" width="800">'; svg += '<text x="0" y="0" We also need: function imgLoaded(img) { return new Promise( resolve => { img.onload = () => { resolve(img); }; } ); } Notice that we are using promises and so it is assumed that ECMA 2015 is available. Also notice that the text that you draw has to fit into an 80x800 area - you can increase the size if this is too small. Using the function is easy: text(ctx, x, y, text, style) This renders the string in text on the canvas context ctx at position x,y using the style specified in style. The only problem is in specifying the SVG style in a string with single and double quotes. For example: text(ctx,100,100,"Hello SVG Text!", 'font-family="symbol" font-size="20pt"'); produces: The typographic controls are another issue. For example, you can use x="0" y="0" to set the position of the text to 0,0, but you can also supply a list of values that will be used to position each letter in the string. If you just want to add an increment then you can also use dx and dy and again specify a list. For example: text(ctx, 50,50,"H2O is water", 'dy="0,8,-8"'); produces: You can also specify a rotation for each character using rotate= and a list of angles in degrees: text(ctx,100,100,"Hello SVG Text!",'font-family="serif" font-size="20pt" rotate="90,45,60,33,22,34,55"'); The final angle applies to the remaining characters: You can adjust the letter spacing: text(ctx,10,100,"Hello SVG Text!",'font-family="serif" font-size="20pt" letter-spacing="4"'); This produces: You can also adjust word spacing, kerning, and even word wrap for multline text. If you need to change the format in part of a string then use the <tspan> tag. For text to a path use <textpath>, but you will also need to set an SVG path before rendering. Look up SVG text or CSS text styling. In chapter but not in this extract
Summary
Now available as a paperback or ebook from Amazon.JavaScript Bitmap Graphics
|
|||
Last Updated ( Saturday, 09 November 2019 ) |