It is required to create an invitation card page, in which the number of words in the title is dynamic and can display up to 2 lines. If it exceeds 2 lines, an ellipsis will be added at the end of the second line of content. According to the personality of the product girl, there is a high chance that the setting of four lines will be changed in the future, so it must not be hard-coded here. As a result, a few days ago, I actually asked to change it to display up to 4 lines, and the others remain the same. The product girl is too young:)!
Without further ado, here’s the code to show off! Before loading the code, take a look at the parameters that need to be passed! !
Parameter descriptions with pictures and texts, forgive me for my impatient PS technology and design
// Text automatic line wrapping function textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) { var drawTxt = ''; // The currently drawn content var drawLine = 1; // Which line to start drawing var drawIndex = 0; // Index of the current drawing content // Determine whether the content can be drawn in one line if(ctx.measureText(content).width <= lineMaxWidth) { ctx.fillText(content.substring(drawIndex, i), drawX, drawY); } else { for (var i = 0; i <= content.length; i++) { drawTxt += content[i]; if (ctx.measureText(drawTxt).width > lineMaxWidth) { if (drawLine === lineNum) { // Add an ellipsis to the last line ctx.fillText(content.substring(drawIndex, i) + '...', drawX, drawY); break; } else { // If it is not the last line, ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY); drawIndex = i + 1; // Record the next idnex of the last string of the current line, which is used to draw the first word of the next line drawLine += 1; // Number of lines + 1 drawY += lineHeight; // The y coordinate of the drawn content increases the line height accordingly drawTxt = ''; // Reset the drawn content } } } }}unexpected discovery
In the process of drawing text, I found that the y coordinate of drawing text should be based on the top of the text. A picture is worth more words, the picture above!
Browser environment: chrome 71.0.3578.98 (official version) (64-bit)
Font size is 40px
When the drawn y coordinate is 0, you can see that the text only leaks out a little bit in the upper left corner.When the y coordinate is drawn at 40, you can see that the text can be fully displayed
postscriptThis is a relatively unpopular code effect, but I hope it can help friends in need. I also hope everyone will support VeVb Wulin Network.