HTML5 canvas ctx.fillText won't do line breaks

HTMLWeb DevelopmentFront End Technology

The fillText() method draws filled text on the canvas. If you want to break lines you can do this by splitting the text at the new lines and calling the filltext() multiple times. By doing so, you are splitting the text into lines and drawing each line separately.

You can try to run the following code snippet −

var c = $('#c')[0].getContext('2d');
c.font = '12px Courier';

var str = 'first line \nsecond line...';
var a = 30;
var b = 30;
var lineheight = 15;
var lines = str.split('\n');

for (var j = 0; j<lines.length; j++)
c.fillText(lines[j], a, b + (j*lineheight) );
// for canvas
<canvas id="c" width="200" height="200"></canvas>

// CSS

canvas {
   background-color: #FFCE9E;
Published on 20-Mar-2018 15:50:45