Open Technical Blog
Wednesday, 9 December 2015
Input field on top of a canvas
This page shows how to place an input field on top of a canvas.
Press on the green area to open up an input field
Change text inside the field
Press Enter to confirm
Press Esc to cancel
Source Code
var context, canvas; var gCnvW = 0; var gCnvH = 0; var gCnvT = 0; var gCnvL = 0; var gTxt00 = ''; var gTxt01 = '\u25c0 Press me to open up a text box.'; function init() { canvas = document.getElementById("myCanvas"); context = canvas.getContext("2d"); gInp = document.getElementById("myInput"); gCnvT = canvas.offsetTop; gCnvL = canvas.offsetLeft; gCnvW = canvas.width; gCnvH = canvas.height; canvas.addEventListener('touchstart', doTouchStart,false); canvas.addEventListener("mousedown", onMouseDown, false); gInp.addEventListener('keydown', doKeyDown, false); return setInterval(draw, 100); } function getMousePos(pEvnt) { var mx = 0; var my = 0; if (pEvnt.offsetX != undefined) { mx = pEvnt.offsetX; my = pEvnt.offsetY;} else { mx = pEvnt.layerX; my = pEvnt.layerY;} return [mx,my]; } function getTouchPos(pEvnt) { var mx = pEvnt.targetTouches[0].pageX - gCnvL; var my = pEvnt.targetTouches[0].pageY - gCnvT; return [mx,my]; } function doTouchStart(pEvnt) { var mPos = getTouchPos(pEvnt); actionStart(pEvnt,mPos[0],mPos[1]); } function onMouseDown(pEvnt) { var mPos = getMousePos(pEvnt); actionStart(pEvnt,mPos[0],mPos[1]); } function doKeyDown(pEvnt) { var mkey = pEvnt.keyCode; if (mkey==27) { // cancel input gInp.type = 'hidden'; } else if (mkey==13) { // confirm input gTxt01 = gInp.value; gInp.type = 'hidden'; } } function actionStart(pEvnt,pX,pY) { pEvnt.preventDefault(); var mxs = pX.toFixed(0) var mys = pY.toFixed(0); if (pX>50 && pX<110 && pY>50 && pY<110) { gTxt00 = 'x: '+mxs+' y: '+mys; gInp.value = gTxt01; gCnvT = canvas.offsetTop; gCnvL = canvas.offsetLeft; var mx = 130+gCnvL; var my = 80+gCnvT; gInp.style.left=mx.toString()+'px'; gInp.style.top=my.toString()+'px'; gInp.style.width='400px'; gInp.style.fontSize='20px'; gInp.type = 'text'; gInp.focus(); } } function draw() { context.clearRect(0,0,gCnvW,gCnvH); // show touch coor. context.font = "bold 14px Sans-Serif"; context.fillText(gTxt00, 10, 20); // draw button context.fillStyle = 'green'; context.fillRect(50,50,60,60); // show output field context.fillStyle = 'black'; context.font = "bold 20px Sans-Serif"; context.fillText(gTxt01, 130, 70); // adjust input field if (gInp.type=='text') { gCnvT = canvas.offsetTop; gCnvL = canvas.offsetLeft; var mx = 130+gCnvL; var my = 80+gCnvT; gInp.style.left=mx.toString()+'px'; gInp.style.top=my.toString()+'px'; } } init();
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment