Make a javascript canvas rectangle clickable -
i creating simple calculator. here is. done basic design confused on how make buttons clickable? 1 trick make div each button think there has simple way. please guide.
<!doctype html> <html> <body> <canvas id="mycanvas" width="300" height="400" style="border:2px solid ;"> browser not support html5 canvas tag.</canvas> <script> var c=document.getelementbyid("mycanvas"); var ctx=c.getcontext("2d"); ctx.moveto(0,80); ctx.lineto(300,80); ctx.fillstyle="#333333"; ctx.fillrect(0,320,50,80); ctx.fillstyle="#333333"; ctx.fillrect(250,320,50,80); ctx.stroke(); </script> </body> </html>
you can “press” drawn key on canvas listening mouseclicks , hittesting whether click position inside 1 of calculator key’s boundary.
here code return true if mouseclick inside rectangle:
function ispointinsiderect(pointx,pointy,rectx,recty,rectwidth,rectheight){ return (rectx <= pointx) && (rectx + rectwidth >= pointx) && (recty <= pointy) && (recty + rectheight >= pointy); }
if calculator buttons round, here code hittest mouseclick inside circle:
function ispointinsidecircle(pointx,pointy,circlex,circley,radius){ var dx=circlex-pointx; var dy=circley-pointy; return ( dx*dx+dy*dy<=radius*radius ); }
Comments
Post a Comment