Wrap and input Canvas

by vijayweb

HTML

<canvas width="350" height="180" id="cnv1"></canvas>
	<br/> Text:
	<input type="text" id="text_cnv" size="40" maxlength="250" />

JavaScript

function clearCanvas(cnv) {
		var ctx = cnv.getContext('2d');
		ctx.beginPath();
		ctx.save();
		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.clearRect(0, 0, cnv.width, cnv.height);
		ctx.restore();
	}

	function addTextCnv(ctx, text, x, y, maxWidth, lineHeight) {
		var words = text.split(' ');
		var nr_w = words.length
		var addtxt = '';
		for (var n = 0; n < nr_w; n++) {
			var txtLine = addtxt + words[n] + ' ';
			var metrics = ctx.measureText(txtLine);
			var txtWidth = metrics.width;
			if (txtWidth > maxWidth && n > 0) {
				ctx.fillText(addtxt, x, y);
				addtxt = words[n] + ' ';
				y += lineHeight;
			} else addtxt = txtLine;
		}
		ctx.fillStyle = '#0001be';
		ctx.font = 'bold 17px sans-serif';
		ctx.fillText(addtxt, x, y);
	}
	var cnv1 = document.getElementById('cnv1');
	var ctx1 = cnv1.getContext('2d');
	var maxWidth = cnv1.width - 10;
	var lineHeight = 23;
	var x_pos = (cnv1.width - maxWidth) / 2;
	var y_pos = 15;
	document.getElementById('text_cnv').onkeyup = function () {
			clearCanvas(cnv1);
			addTextCnv(ctx1, this.value, x_pos, y_pos, maxWidth, lineHeight);
		}