【问题标题】:How to stretch text value in konvaJS to certain width and height?如何将 konvaJS 中的文本值拉伸到一定的宽度和高度?
【发布时间】:2016-08-22 15:02:54
【问题描述】:

在 KonvaJS 文本对象中有一个 fontSize 属性,例如 fontSize: 30,但我需要根据我为其指定的宽度和高度来拉伸文本。

这是我写的:

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

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

【问题讨论】:

  • @lavrton KonvaJS 库中应该有一些简单的东西吗?
  • 我的答案中的 scaledFontsize 函数只有 6 行简单的行......这很简单。 :-)
  • @markE 创建过多的画布不利于记忆。
  • 只有 1 个画布,它只是临时创建的。垃圾收集器会很快回收内存。您甚至可以以零内存占用运行scaledFontSize。由于画布并未用于实际绘制,因此您可以获得对 Kinetic/Konva 画布的引用并将其用于measureText。 :-)

标签: javascript canvas kineticjs konvajs


【解决方案1】:

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

  • 创建内存中的画布元素,
  • 以特定的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>

【讨论】:

    猜你喜欢
    • 2010-12-24
    • 2014-01-22
    • 2019-12-14
    • 2015-09-03
    • 2017-02-01
    • 1970-01-01
    • 2019-10-30
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多