JsFiddle: http://jsfiddle.net/K34a7/ I am creating a div and saving image in it. I want to know how to detect the width of the part written in image so that i can dynamically assign the width size of the div and not the whole image?
document.getElementById('text').addEventListener('keyup', function (){
tCtx.canvas.width = tCtx.measureText(this.value).width;
var t = this.value.split('\n');
tCtx.canvas.height = t.length*10;
console.log(t);
var y = 10;
for(var i=0; i<t.length; i++, y+=10) {
tCtx.fillText(t[i], 0, y);
}
//console.log('Value: ' + this.value);
imageElem.src = tCtx.canvas.toDataURL();
//console.log(imageElem.src);
}, false);
You’re already using
measureTextin your code. Just add a reference to the width like sotextWidthwill contain the width of the text on the canvas.Demo