Konva.js: how to fit text in a box


Online demo: https://jsbin.com/zeyebukayo/edit?html,js,output

how to fit text in a box

HTML

<!DOCTYPE html>
<html>
<head>
<meta name="description" content="KonvaJS Template">
  <script src="https://cdn.rawgit.com/konvajs/konva/1.4.0/konva.min.js"></script>
  <meta charset="utf-8">
</head>
<body>
  <div id="container"></div>
</body>
</html>

JAVASCRIPT

console.clear();
var stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight
});

var layer = new Konva.Layer();
stage.add(layer);

var newSize = [400,200];

var text = new Konva.Text({
  x: 0,
  y: 0,
  text: 'TUTORIALSPOTS.COM',
  fontSize: 14,
  fontFamily: 'Arial',
  fill: 'green',
  draggable: true
});
layer.add(text);
 
// get bounding rectangle
var box = text.getClientRect({relativeTo: layer});

//caculate scales
var scale = [
  newSize[0] / (box.width),
  newSize[1] / (box.height)
];
 
text.setAttrs({
  scaleX: scale[0],
  scaleY: scale[1]
});

layer.draw();

CSS

body{
  margin: 0;
}

Leave a Reply