Skip to content

Instantly share code, notes, and snippets.

@derekmc
Created April 29, 2021 16:24
Show Gist options
  • Select an option

  • Save derekmc/c136e1b32079e46a640a692c071a2842 to your computer and use it in GitHub Desktop.

Select an option

Save derekmc/c136e1b32079e46a640a692c071a2842 to your computer and use it in GitHub Desktop.
<canvas id=Canvas></canvas>
<script>
let text = "> Hello,\n World.";
let Margin = 10;
let LineHeight = 14;
function Draw(){
let ctx = Canvas.getContext("2d");
ctx.font = "13px monospace"
ctx.fillStyle = "#dedede";
ctx.fillRect(0, 0, Canvas.width, Canvas.height);
ctx.fillStyle = "black";
let lines = text.split(/\n/);
let w = Canvas.width - 2 * Margin;
for(let i=0, j=0; i<lines.length; ++i, ++j){
let line = lines[i];
console.log("Line", line);
if(ctx.measureText(line).width > w){
let dlength = Math.floor(line.length / 2);
let k = line.length - dlength;
while(dlength > 1){
dlength = Math.floor(dlength/2);
while(ctx.measureText(line.substring(0, k)).width < w){
k += dlength; }
while(ctx.measureText(line.substring(0, k)).width > w){
k -= dlength; }
}
console.log("Line length", k);
lines[i] = line.substring(k);
line = line.substring(0, k);
--i;
}
console.log("Line", line);
console.log("Remaining Line", lines[i+1]);
ctx.fillText(line, Margin, Margin + LineHeight * (j + 0.5));
}
}
document.body.addEventListener("keydown", (e) => {
let c = e.key;
if(c == "Backspace") text = text.substring(0, text.length - 1);
else if (c == "Enter") text += "\n";
else if (c.length == 1) text += c;
Draw();
})
window.addEventListener('load', Draw);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment