javascript - Canvas element: Image clicked -
i want know if user clicked on image drawed in canvas. click on image nothing happens. alert isn't called. last if condition never pass. idea?
<!doctype html> <html> <head> </head> <body> <div id="wrapper"> <canvas id="game" height="500" width="700"> </canvas> </div> <script> (function() { var canvas = document.getelementbyid('game'), context = canvas.getcontext('2d'), fps = 1, character = image(), positions = [[125, 55], [480, 55], [125, 185], [480, 182], [125, 315], [480, 315]], random, x, y, xc, yc = null; canvas.addeventlistener('click', function(event) { xc = event.screenx - canvas.offsetleft; yc = event.screeny - canvas.offsettop; if((xc >= x) && (xc <= (x + character.width)) && (yc >= y) && (yc <= (y + character.height))) { alert('x = ' + x + 'y = ' + y); } }, true); character.src = 'character.png'; setinterval(function() { random = (math.floor(math.random() * 6)); random = positions[random]; x = random[0]; y = random[1]; context.clearrect(0, 0, canvas.width, canvas.height); context.drawimage(character, x, y); }, 1000 / fps); }()); </script> </body> </html>
two problems here.
first, event code broken screenx returns mouse position relative screen, need use clientx or in ie pagex see quirksmode more information.
canvas.addeventlistener('click', function(event) { event = event || window.event; // ie not pass event param! // should use var infront of these local variables // otherwise leak them global namespace // , can overwrite things there if don't watch out var xc = (event.clientx ? event.clientx : pagex) - canvas.offsetleft; var yc = (event.clienty ? event.clienty : pagey) - canvas.offsettop; second, code never runs in chrome! fails uncaught typeerror: dom object constructor cannot called function. @ line 15. need use new keyword when creating image, since it's not guaranteed otherwise, image() return new instance.
... context = canvas.getcontext('2d'), fps = 1, character = new image(), ...
Comments
Post a Comment