2016-08-22 129 views
1

在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創造太多的畫布是不友善的內存。 –

回答

0

文本字體可能不會逐漸縮放到完全符合所需寬度,但您可以靠近。

  • 創建一個內存中的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>

相關問題