html5 canvas 画一个矩形,文字超出矩形怎样自动换行? 10C

DrawingManager.prototype.showLayerTitle = function (layer, isSelected) {
let x, y;
if (layer.p1) {

    x = layer.p1.x1 + layer.x + 5, y = layer.p1.y1 + layer.y + 5;
} else {
    x = layer.x + 5, y = layer.y + 5;
}

this.$canvas.drawText({
    name: layer.name + "_title",
    layer: true,
    cursors: {
        mouseover: 'hand'
    },
    fromCenter: false,
    fillStyle: '#9cf',
    strokeStyle: isSelected ? '#03e2dc' : '#d3e2dc',
    strokeWidth: 1,   //笔划宽度
    shadowColor: 'black',  //阴影颜色
    shadowBlur: 2,   //阴影模糊
    shadowOffsetX: 2,
    shadowOffsetY: 2,
    groups: ['grpTitle'],
    x: x, y: y,
    fontSize: isSelected ? 16 : 14,
    // fontFamily: 'Verdana, sans-serif',
    text: layer.data.title === '' ? '...':layer.data.title,
    click: () => {
        if(this.canvasDrawingModel === 0){
            saveCategory(layer.data.title, layer.name);
        }
    }
})

};
如何让text换行

2个回答

<canvas id="canvasId" width="400" height="350"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvasId");
var ctx = canvas.getContext("2d");
var str = "我爱你 I love you 你好你好你好你好你好你好你好";
var textWidth = 400;
var cx = 0;
var cy = 0;
ctx.font = "30px Arial";
ctx.lineWidth = 30;
ctx.textBaseline = "top";
while (str.length>0) {
    for (var i = 0; i < str.length; i++)
        if (ctx.measureText(str.substring(0,i+1)).width>textWidth)
            break;
    ctx.fillText(str.substring(0,i),cx,cy);
    str = str.substring(i);
    cy += ctx.lineWidth;
}
</script>

 var c=document.getElementById("canvas"); 
var ctx=c.getContext("2d"); 
ctx.fillStyle="#E992B9";
ctx.lineWidth=1; 
var str = "假如生活欺骗了你,请不要悲伤!thank you!"
var lineWidth = 0;
var canvasWidth = c.width;//计算canvas的宽度
var initHeight=15;//绘制字体距离canvas顶部初始的高度
var lastSubStrIndex= 0; //每次开始截取的字符串的索引
for(let i=0;i<str.length;i++){ 
    lineWidth+=ctx.measureText(str[i]).width; 
    if(lineWidth>canvasWidth){  
        ctx.fillText(str.substring(lastSubStrIndex,i),0,initHeight);//绘制截取部分
        initHeight+=20;//20为字体的高度
        lineWidth=0;
        lastSubStrIndex=i;
    } 
    if(i==str.length-1){//绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex,i+1),0,initHeight);
    }
}

https://blog.csdn.net/lishihong108/article/details/52483867?ref=myread

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐