It's free and you have access to premium codes!
Welcome back! Please login to your account.
Don't worry, we'll send you a message to help you to recover your acount.
Please check your email for instructions to activate your account.
Written by 26 June 2013
You may want to create a graphical Canvas which needs that ask something from the users or a key to get pressed. HTML allows you to detect the pressed key by Javascript. Then you can manage the pressed key and make a relationship between it and HTML5 Canvas and define different actions for it. For example it is also possible to move an object by a keyboard key. The following example asks for the user's name and wrote it on the Canvas Context. Note that to avoid complexity we don't have defined special keys such as Shift or Backspace and it is just a simple writing program. (To make the preview below work, click on the preview frame)
<!-- this script is provided by https://www.html5freecode.com coded by: Kerixa Inc. -->
<canvas id="myCanvas" width="400" height="230" ></canvas>
<script>
var cnv = document.getElementById('myCanvas')
var ctx = cnv.getContext('2d')
var t1, ch, txt,w
window.addEventListener("keyup", Type, true);
w=0
txt=''
t1='Enter Your Name:'
ctx.font= "bold 30pt serif"
ctx.fillStyle= "gray"
ctx.fillRect(0, 160, 400, 2)
ctx.fillStyle= 'Blue'
ctx.strokeText(t1, 5, 60)
ctx.fillText(t1, 5, 60)
ctx.fillStyle= 'blue'
ctx.beginPath()
ctx.fillRect(8,120,2,40)
function Type(e){
if (e.keyCode<112){
ctx.fillStyle='white'
ctx.beginPath()
ctx.fillRect(8+w,120,2,40)
ctx.strokeStyle='black'
ch= String.fromCharCode(e.keyCode)
txt+= ch
w= ctx.measureText(txt).width
ctx.fillStyle= 'Brown'
ctx.strokeText(txt, 5, 160)
ctx.fillText(txt, 5, 160)
}
ctx.fillStyle= 'blue'
ctx.beginPath()
ctx.fillRect(8+w,120,2,40)
}
</script>
<div style="text-align: left"><font face="Tahoma"><br><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='https://www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>
Comments
Here you can leave us commments. Let us know what you think about this code tutorial!