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

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

WBOY
WBOYOriginal
2016-06-24 12:15:052670browse

   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();

Can’t change the line!!!
Is there any way to change the line? ? ?


Reply to discussion (solution)

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn