javascript - Drawing a circle on HTML5 canvas at touch location -
basically, i'm trying use javascript when button pressed on page, begin listening next touch on canvas. on touch, function triggered gets x , y co-ordinates of touch , draws circle there. circle needs labelled well, have put in prompt label. here attempt , bit of context:
<input type="button" value="add symptom" onclick="touch_init();">
when above input button pressed following triggered:
function touch_init(){ var canvas = document.getelementbyid("medicanvas"); canvas.addeventlistener("touchstart", drawsymptomcircle, false); } function drawsymptomcircle(event) { var canvas = document.getelementbyid("medicanvas"); if (canvas.getcontext){ var ctx = canvas.getcontext("2d"); var x = new number(); var y = new number(); var radius = 100; var symptomname=prompt("please enter name of symptom:"); x = event.targettouches[0].pagex; y = event.targettouches[0].pagey; x-=canvas.offsetleft; y-=canvas.offsettop; ctx.beginpath(); ctx.arc(x, y, radius, 0, 2 * math.pi, false); ctx.fillstyle = "rgb(0,128,255)"; ctx.fill(); ctx.linewidth = 2; ctx.strokestyle = "black"; ctx.stroke(); ctx.font = '15pt calibri'; ctx.fillstyle = 'black'; ctx.textalign = 'center'; ctx.filltext(symptomname, x, y); canvas.removeeventlistener("touchstart", drawsymptomcircle, false); } }
edit: draws circles inside canvas, not @ 0,0 , not drawn in right places. why not in correct place?
use clientx/y instead , use bounding rect compensate canvas position:
function drawsymptomcircle(event) { var canvas = this; // no need canvas element dom, = canvas if (canvas.getcontext){ // test should done once in global, not here :) ... var rect = this.getboundingclientrect(); // absolute position of canvas x = event.targettouches[0].clientx; // relative client win y = event.targettouches[0].clienty; x -= rect.left; // adjusted relative canvas y -= rect.top; ...
also obtaining getcontext() recommend in global/parent scope. this
represent canvas element element default context event handler.
Comments
Post a Comment