Home >Web Front-end >HTML Tutorial >html5 canvas draws a rectangle and adds text in the rectangle. How to wrap text automatically if it exceeds the rectangle? ? ? _html/css_WEB-ITnose
var canvas = document.getElementById("demo") var ctx = canvas.getContext('2d'); ctx.font = "32pt Arial"; ctx.beginPath(); ctx.lineWidth = "1"; ctx.strokeStyle = "blue"; ctx.moveTo(100, 100); ctx.lineTo(100, 400); ctx.lineTo(400, 400); ctx.lineTo(400, 100); ctx.closePath(); ctx.stroke(); ctx.strokeText("hello world hello world hello world hello world hello world", 120, 200); ctx.strokeStyle = "red"; ctx.stroke();
I’m afraid it’s impossible for CANVAS to automatically wrap text, because the drawn text has nothing to do with the rectangle.
Only the text itself is based on the rectangle. After calculating the size and position, draw the text
Calculate the width of the text to wrap the line
If you are worried about calculation trouble, you can use a fixed-width font