如何将konvaJS中的文本值拉伸到一定的宽度和高度?

问题描述:

在KonvaJS文本对象中有一个属性fontSizefontSize: 30但我需要根据我给它的宽度和高度来拉伸文本。如何将konvaJS中的文本值拉伸到一定的宽度和高度?

这里是我写的:

var textX = new Konva.Text({ 
 
      text: 'X', 
 
      align: 'center', 
 
      x: 60, 
 
      y: 60, 
 
      width: 60, 
 
      height: 40 
 
     });

你有什么建议让代码工作?

+0

@lavrton应该有东西在KonvaJS库简单? –

+1

我的答案中的'scaledFontsize'函数只有6条简单的线条......很简单。 :-) – markE

+0

@markE创造太多的画布是不友善的内存。 –

文本字体可能不会逐渐缩放到完全符合所需宽度,但您可以靠近。

  • 创建一个内存中的canvas元素,
  • 在一定px testFontsize(几乎任何合理的测试规模将做)测量你的文字,
  • 所需的字体大小:testFontsize*desiredWidth/measuredWidth
  • 套装Konva.Text中需要的字体大小为px

注:有些字体不小数精确缩放,所以你可能要.toFixed(0)所产生的缩放字体大小。有些字体可能无法按比例增加缩放比例,您将获得最接近的可用字体大小 - 这可能无法很好地填充所需的宽度。

示例代码:

var canvas=document.getElementById("canvas"); 
 
var ctx=canvas.getContext("2d"); 
 
var cw=canvas.width; 
 
var ch=canvas.height; 
 

 
// define the desired text, fontsize and width 
 
var text='Scale Me'; 
 
var fontface='verdana'; 
 
var desiredWidth=60; 
 

 
$myslider=$('#myslider'); 
 
$myslider.attr({min:30,max:200}).val(desiredWidth); 
 
$myslider.on('input change',function(){ 
 
    desiredWidth=parseInt($(this).val()); 
 
    ctx.clearRect(0,0,cw,ch); 
 
    draw(text,fontface,desiredWidth) 
 
}); 
 

 
draw(text,fontface,desiredWidth); 
 

 
function draw(text,fontface,desiredWidth){ 
 
    // calc the scaled fontsize needed to fill the desired width 
 
    var scaledSize=scaledFontsize(text,fontface,desiredWidth); 
 
    // Demo: draw the text at the scaled fontsize 
 
    ctx.font=scaledSize+'px '+fontface; 
 
    ctx.textAlign='left'; 
 
    ctx.textBaseline='middle'; 
 
    ctx.strokeRect(0,0,desiredWidth,100); 
 
    ctx.fillText(text,0,50); 
 
    ctx.font='14px verdana'; 
 
    ctx.fillText(scaledSize+'px '+fontface+' fits '+desiredWidth+'px width',10,125); 
 
} 
 

 
function scaledFontsize(text,fontface,desiredWidth){ 
 
    var c=document.createElement('canvas'); 
 
    var cctx=c.getContext('2d'); 
 
    var testFontsize=18; 
 
    cctx.font=testFontsize+'px '+fontface; 
 
    var textWidth=cctx.measureText(text).width; 
 
    return((testFontsize*desiredWidth/textWidth)); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
Desired Width:&nbsp<input id=myslider type=range><br> 
 
<canvas id="canvas" width=300 height=256></canvas>