Canvas How to - Show what you typed in text input on canvas








Question

We would like to know how to show what you typed in text input on canvas.

Answer


<!--from  w  ww .j  a  va 2  s.c  o m-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
canvas {
   border:1px solid red;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
        function draw(event) {
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            var text = document.getElementById('item').value
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "#3e3e3e";
            ctx.font = "16px Arial";
            ctx.fillText(text, 50, 50);
        }
        window.addEventListener("keyup", draw, true);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=300></canvas>
<br/>
<input type="text" id="item">
</body>
</html>

The code above is rendered as follows: