Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@setkyar
Created March 15, 2016 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save setkyar/0127cef67902da111659 to your computer and use it in GitHub Desktop.
Save setkyar/0127cef67902da111659 to your computer and use it in GitHub Desktop.
Line break on canvas
<canvas id="myCanvas" width="720" height="379" style="border:1px solid"></canvas>
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var maxWidth = 400;
var lineHeight = 25;
var x = 300;
var y = 60;
var text = 'မြန်မာလိုနဲ့ English လိုတွဲရေးရင်အဆင်ပြေလားခင်ဗျာ... ပြန်ကြမယ်... ပြန်ကြမယ်... တာတာတာတာတာ တတာတာတာတား တာတ';
context.font = '16pt Calibri';
context.fillStyle = '#333';
wrapText(context, text, x, y, maxWidth, lineHeight);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment