2016-08-22 9 views
1

KonvaJSテキストオブジェクトでは、fontSizeのようにfontSize: 30のようなものがありますが、幅と高さに応じてテキストを伸ばす必要があります。ここでkonvaJSで特定の幅と高さにテキスト値を伸ばす方法は?

は私が書いた:

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

あなたは、コードの仕事を聞かせすることをお勧めしますか?

+0

KonvaJSライブラリで簡単な何かがあるはず@lavrton? –

+1

私の答えの 'scaledFontsize'関数は単純な6行だけです...それは簡単です。 :-) – markE

+0

@markEあまりにも多くのキャンバスを作ることは、メモリにはやらない。 –

答えて

0

テキストフォントは、目的の幅に正確に収まるように段階的に縮尺されない場合がありますが、近づけることができます。

  • 必要なフォントサイズがある
  • 、特定のpx testFontsize(ほぼすべての合理的なテストサイズが行います)で、あなたのテキストを測定します
  • 、メモリ内のcanvas要素を作成します:
  • 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>

関連する問題