Canvas- Make Graphical Buttons by a Function

Written by @m_k_amin 30 June 2013

When HTML5 Canvas element is used, there is no way to define HTML standard form elements; so if you need a button you can not create it easily. The following code is a function for creating buttons inside HTML5 Canvas element. You can set filling Style of the button when the mouse cursor comes in, goes out and when the button is pressed. It is also possible to define button text, its font style and color. If the text is bigger than the button width, it is automatically adjusted. If you fill that simple colors are boring, no problem, define a gradient and put it as the button color. A function name and its arguments can passed into the button creation function; so when the button is pressed, it will get ran. You can easily add different features to the function below, but if you are a beginner, leave the function definition codes and just learn how to use it. Enjoy!

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.html5freecode.com coded by: Kerixa Inc. -->
<body>

<canvas id="myCanvas" width="400" height="230" onmousemove="DrawAll(event)" onmousedown="mouse(event,1)" onmouseup="mouse(event,0)"></canvas>

<script>

    var cnv = document.getElementById('myCanvas')

    var ctx = cnv.getContext('2d')

    var deg = Math.PI/180

	

	var RadGrad= ctx.createRadialGradient(70, 45, 1, 20, 45, 180)

	RadGrad.addColorStop(0, "rgba(1, 150, 225, 0.5)")

	RadGrad.addColorStop(0.33, "rgba(2, 30, 225, 0.9)")

	RadGrad.addColorStop(0.66, "rgba(78, 1, 225, 0.9)")	

	RadGrad.addColorStop(1, "rgba(155, 1, 225, 0.5)")



	DrawAll(null)


function DrawAll(e){

	ctx.clearRect(0,0, cnv.offsetWidth, cnv.offsetHeight)

	CreateButton(20,20,100,50, 'OK', "20pt serif", 'fnc', 'OK is pressed!', 'lightblue', RadGrad, 'lightgray', 'brown', e)

	CreateButton(150,20,70,100, 'Cancel', "20pt serif", 'fnc', 'Cancel is Pressed!', 'darkblue', 'brown', 'lightblue', 'yellow', e)

	CreateButton(20,140,250,80, 'Done', "40pt serif", 'fnc', 'Done is Pressed!', '#2DC399', 'darkgreen', '#EED3F1', 'magenta', e)	

}



function fnc(msg){

	document.getElementById('tDiv').innerHTML= msg

}




// Don't change these:

var mp=0, ff=0

function CreateButton(x, y, w, h, txt, fontStyle, clickFuncName, args, clrIn, clrOut, clrClick, txtClr, event){

	var rw= w/5, rh= h/3

	var txtClr2= txtClr

		

	ctx.beginPath()

	ctx.moveTo(x+rw, y)

	ctx.lineTo(x+w-rw, y)

	ctx.quadraticCurveTo(x+w, y, x+w, y+rh)

	ctx.lineTo(x+w, y+h-rh)

	ctx.quadraticCurveTo(x+w, y+h, x+w-rw, y+h)

	ctx.lineTo (x+rw, y+h)

	ctx.quadraticCurveTo(x, y+h, x, y+h-rh)

	ctx.lineTo(x, y+rh)

	ctx.quadraticCurveTo(x, y, x+rw, y)

	ctx.closePath()

	

	if (event!=null){

		if (!IsInPath(event)){ 

			ctx.fillStyle= clrOut

		}else{

			if (mp==0){

				ctx.fillStyle= clrIn

				if (ff==1) ff=2

			}else{

				ctx.fillStyle= clrClick

				txtClr2= clrClick

				ff=1

			}

		}

	} else 

		ctx.fillStyle= clrOut

	ctx.strokeStyle= 'black'

	ctx.stroke()

	ctx.fill()

	

   	ctx.font= fontStyle

	ctx.textAlign= 'left'

	ctx.textBaseline= 'middle'

	tw=ctx.measureText(txt).width   		

	if (tw>(w-10)) tw= w-10	

	ctx.fillStyle= txtClr2

	ctx.strokeStyle= txtClr

    ctx.fillText(txt, x+w/2 -tw/2, y+h/2, tw)	

    ctx.strokeText(txt, x+w/2 -tw/2, y+h/2, tw)	

	

	if (ff==2){

		executeFunctionByName(clickFuncName,window, args)

		ff=0

	}

}

function IsInPath(event) {

	var bb, x, y

	bb = cnv.getBoundingClientRect()

	x = (event.clientX-bb.left) * (cnv.width/bb.width)

	y = (event.clientY-bb.top) * (cnv.height/bb.height)

	return ctx.isPointInPath(x,y)

}

function mouse(e,s){

	mp=s

	DrawAll(e)

}

function executeFunctionByName(functionName, context /*, args */) {

  var args = Array.prototype.slice.call(arguments).splice(2);

  var namespaces = functionName.split(".");

  var func = namespaces.pop();

  for(var i = 0; i < namespaces.length; i++) {

    context = context[namespaces[i]];

  }

  return context[func].apply(this, args);

}

</script>

<div id="tDiv" style="color: #2D3AC3; font-size: large">Event</div>



<div style="text-align: left"><font face="Tahoma"><br><a target="_blank" href="https://html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div>

</body><a target='_blank' href='https://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

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: Afzal, FOTPU
advertisement 2