Canvas- Working with Keyboard and Detect Pressed Key

Written by @m_k_amin 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)

Code Snippet:

                                                
                                                <!-- this script is provided by 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='www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M
TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members:
advertisement 2