javascript - Simple Button in HTML5 canvas -
javascript - Simple Button in HTML5 canvas -
i new javascript , in process of making project web based (html) basic knowledge have managed create form , drawn rectangle on it.
i able click rectangle , using button cannot seem find tutorials or answers can help me.
this code rectangle :
function playbutton(top, left, width, height, lwidth, fillcolor, linecolor) { context.beginpath(); context.rect(250, 350, 200, 100); context.fillstyle = '#ffffff'; context.fillstyle = 'rgba(225,225,225,0.5)'; context.fillrect(25,72,32,32); context.fill(); context.linewidth = 2; context.strokestyle = '#000000'; context.stroke(); context.closepath(); context.font = '40pt kremlin pro web'; context.fillstyle = '#000000'; context.filltext('start', 345, 415); }
i aware need find x,y coordinates , mouse position in order click in area of rectangle. i'm stuck @ point. maybe simple , logic, have had go past stage.
you thinking in right direction. can solve multiple ways using html button suggested in comments.
but if need handle click events within canvas can this:
add click handler canvas , when mouse pointer within bounding rectangle can fire click function:
//function mouse position function getmousepos(canvas, event) { var rect = canvas.getboundingclientrect(); homecoming { x: event.clientx - rect.left, y: event.clienty - rect.top }; } //function check whether point within rectangle function isinside(pos, rect){ homecoming pos.x > rect.x && pos.x < rect.x+rect.width && pos.y < rect.y+rect.heigth && pos.y > rect.y } var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); //the rectangle should have x,y,width,height properties var rect = { x:250, y:350, width:200, heigth:100 }; //binding click event on canvas canvas.addeventlistener('click', function(evt) { var mousepos = getmousepos(canvas, evt); if (isinside(mousepos,rect)) { alert('clicked within rect'); }else{ alert('clicked outside rect'); } }, false);
jsfiddle javascript html5 canvas
Comments
Post a Comment