canvas借助SVG foreignObject实现文本自动换行效果实例页面

回到相关文章 »

效果:

代码:

HTML代码:
<canvas width="300" height="150"></canvas>
<p><textarea cols="40" rows="5">4日,@张继科 立春发表新...嗯所以这是?</textarea></p>
<p><button>绘制</button></p> 
                
JS代码:
var textarea = document.querySelector('textarea');
var button = document.querySelector('button');

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
context.font = '16px sans-serif';

button.addEventListener('click', function () {
    var width = canvas.width;
    var height = canvas.height;
    
    var tempImg = new Image();
    tempImg.width = width;
    tempImg.height = height;
    tempImg.onload = function () {
        // 清除之前的绘制
        context.clearRect(0, 0, width, height);
        context.drawImage(this, 0, 0, width, height);
    };
    tempImg.src = 'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg"><foreignObject width="'+ width +'" height="'+ height +'"><body xmlns="http://www.w3.org/1999/xhtml" style="margin:0;font:'+ context.font +';">'+ textarea.value +'</body></foreignObject></svg>';
});

button.click();