Created
March 15, 2016 11:01
-
-
Save setkyar/0127cef67902da111659 to your computer and use it in GitHub Desktop.
Line break on canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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