Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

I am currently developing an H5 page using Canvas. Some of the text needs to be wrapped because it is beyond the width defined by the background. If you have ever used Canvas, you must have used text drawing. Unfortunately, there is no auto-wrap method for text drawing in Canvas documents. This article will walk you through building a canvas wheel that can wrap itself

Canvas text drawing

There are two methods for text drawing

// Fill the specified position with solid text fillText(text, x, y, StrokeText (text,x,y,[maxWidth]) strokeText(text,x,y,[maxWidth]) strokeText(text,x,y,[maxWidth]) strokeText(text,x,y,[maxWidth]) strokeText(text,x,y,[maxWidth]) strokeText(text,x,y, y) strokeText(text,x,y, y) strokeText(text,x,y, y) strokeText MaxWidth: The maximum width allowed to draw in px unitsCopy the code

When maxWidth is set to less than the width of the text to be drawn, the excess is hidden.

Modified drawing method

There is such a method in the Canvas API

// Detecting a piece of text returns an object containing the specified font width in pixels. context.measureText(text)`Copy the code
Code implementation / / add a method on the prototype of the canvas CanvasRenderingContext2D. Prototype. WrapText = function (canvas, text, x, y, maxWidth, lineHeight) { If (typeof text! ='string' || typeof x ! ='number' || typeof y ! ='number'){ return; } / / if the maximum width is undefined Defaults to 300 px if (typeof maxWidth = = 'undefined') {maxWidth = (canvas && canvas. Width) | | 300; } // if the lineHeight is not defined, it is defined to detect the lineHeight of the canvas text or the default lineHeight of the HTML page 'undefined'){ lineHeight = (canvas.canvas && parseInt(window.getComputedStyle(canvas.canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight) } var arrText = text.split(''); var line = ''; for (var n = 0; n < arrText.length; N ++) {var testLine = line + arrText[n]; Var metrics = canvas.measureText(testLine); var testWidth = metrics.width; If (testWidth > maxWidth &&n > 0) {canvas.fillText(line, x, y); line = arrText[n]; y += lineHeight; } else { line = testLine; } } canvas.fillText(line, x, y); }Copy the code

Canvas: canvas instance lineHeight: newline height

Method of use

Wrap text as shown above.

The last

Thank you for watching this blog, if it is helpful to you, I hope to give 👍 comment collection three even!