<p>What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?</p>

<p>No legacy browser compatibility required, Safari, Opera and Firefox will do.</p>

[{'answer_id': 55723, 'author': 'Brian Gianforcaro', 'author_id': 3415, 'author_profile': 'https://Stackoverflow.com/users/3415', 'pm_score': -1, 'selected': False, 'text': '<p>Hey, this is in dojo, just cause it\'s what I had the code in already for a project.</p>\n\n<p>It should be fairly Obvious how to convert it back to non dojo vanilla JavaScript. </p>\n\n<pre><code>  function onMouseClick(e) {\n      var x = e.clientX;\n      var y = e.clientY;\n  }\n  var canvas = dojo.byId(canvasId);\n  dojo.connect(canvas,"click",onMouseClick);\n</code></pre>\n\n<p>Hope that helps. </p>\n'}, {'answer_id': 1516556, 'author': 'fixermark', 'author_id': 57720, 'author_profile': 'https://Stackoverflow.com/users/57720', 'pm_score': 3, 'selected': False, 'text': '<p>Be wary while doing the coordinate conversion; there are multiple non-cross-browser values returned in a click event. Using clientX and clientY alone are not sufficient if the browser window is scrolled (verified in Firefox 3.5 and Chrome 3.0). </p>\n\n<p><a href="http://www.quirksmode.org/js/events_properties.html" rel="nofollow noreferrer">This quirks mode</a> article provides a more correct function that can use either pageX or pageY or a combination of clientX with document.body.scrollLeft and clientY with document.body.scrollTop to calculate the click coordinate relative to the document origin. </p>\n\n<p>UPDATE: Additionally, offsetLeft and offsetTop are relative to the padded size of the element, not the interior size. A canvas with the padding: style applied will not report the top-left of its content region as offsetLeft. There are various solutions to this problem; the simplest one may be to clear all border, padding, etc. styles on the canvas itself and instead apply them to a box containing the canvas.</p>\n'}, {'answer_id': 4430498, 'author': 'N4ppeL', 'author_id': 540725, 'author_profile': 'https://Stackoverflow.com/users/540725', 'pm_score': 6, 'selected': False, 'text': '<p><strong>Edit 2018:</strong> This answer is pretty old and it uses checks for old browsers that are not necessary anymore, as the <code>clientX</code> and <code>clientY</code> properties work in all current browsers. You might want to check out <a href="https://stackoverflow.com/a/18053642/540725">Patriques Answer</a> for a simpler, more recent solution.</p>\n\n<p><strong>Original Answer:</strong><br>\nAs described in an article i found back then but exists no longer:</p>\n\n<pre><code>var x;\nvar y;\nif (e.pageX || e.pageY) { \n  x = e.pageX;\n  y = e.pageY;\n}\nelse { \n  x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; \n  y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; \n} \nx -= gCanvasElement.offsetLeft;\ny -= gCanvasElement.offsetTop;\n</code></pre>\n\n<p>Worked perfectly fine for me.</p>\n'}, {'answer_id': 5417934, 'author': 'Aldekein', 'author_id': 162118, 'author_profile': 'https://Stackoverflow.com/users/162118', 'pm_score': 4, 'selected': False, 'text': '<p>According to fresh <a href="http://www.quirksmode.org/dom/w3c_cssom.html#mousepos" rel="nofollow noreferrer">Quirksmode</a> the <code>clientX</code> and <code>clientY</code> methods are supported in all major browsers.\nSo, here it goes - the good, working code that works in a scrolling div on a page with scrollbars:</p>\n\n<pre><code>function getCursorPosition(canvas, event) {\nvar x, y;\n\ncanoffset = $(canvas).offset();\nx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);\ny = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;\n\nreturn [x,y];\n}\n</code></pre>\n\n<p>This also requires <a href="https://jquery.com/" rel="nofollow noreferrer">jQuery</a> for <code>$(canvas).offset()</code>.</p>\n'}, {'answer_id': 5928525, 'author': 'Manuel Ignacio López Quintero', 'author_id': 660826, 'author_profile': 'https://Stackoverflow.com/users/660826', 'pm_score': 4, 'selected': False, 'text': '<p>I made a full demostration that works in every browser with the full source code of the solution of this problem: <a href="http://miloq.blogspot.com/2011/05/coordinates-mouse-click-canvas.html" rel="noreferrer">Coordinates of a mouse click on Canvas in Javascript</a>. To try the demo, copy the code and paste it into a text editor. Then save it as example.html and, finally, open the file with a browser.</p>\n'}, {'answer_id': 5932203, 'author': 'Ryan Artecona', 'author_id': 671915, 'author_profile': 'https://Stackoverflow.com/users/671915', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Update</strong> (5/5/16): <a href="https://stackoverflow.com/a/18053642/1026023">patriques\' answer</a> should be used instead, as it\'s both simpler and more reliable.</p>\n\n<hr>\n\n<p>Since the canvas isn\'t always styled relative to the entire page, the <code>canvas.offsetLeft/Top</code> doesn\'t always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a <code>div</code> element containing the canvas with a <code>position: relative</code> style applied. To account for this you need to loop through the chain of <code>offsetParent</code>s, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all. </p>\n\n<pre><code>function relMouseCoords(event){\n    var totalOffsetX = 0;\n    var totalOffsetY = 0;\n    var canvasX = 0;\n    var canvasY = 0;\n    var currentElement = this;\n\n    do{\n        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;\n        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;\n    }\n    while(currentElement = currentElement.offsetParent)\n\n    canvasX = event.pageX - totalOffsetX;\n    canvasY = event.pageY - totalOffsetY;\n\n    return {x:canvasX, y:canvasY}\n}\nHTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;\n</code></pre>\n\n<p>The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that\'s needed to get the useful coordinates is</p>\n\n<pre><code>coords = canvas.relMouseCoords(event);\ncanvasX = coords.x;\ncanvasY = coords.y;\n</code></pre>\n'}, {'answer_id': 6837700, 'author': 'JTE', 'author_id': 766115, 'author_profile': 'https://Stackoverflow.com/users/766115', 'pm_score': 1, 'selected': False, 'text': '<p>In Prototype, use cumulativeOffset() to do the recursive summation as mentioned by Ryan Artecona above.</p>\n\n<p><a href="http://www.prototypejs.org/api/element/cumulativeoffset" rel="nofollow">http://www.prototypejs.org/api/element/cumulativeoffset</a></p>\n'}, {'answer_id': 9961416, 'author': 'Cryptovirus', 'author_id': 1305768, 'author_profile': 'https://Stackoverflow.com/users/1305768', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a small modification to <a href="https://stackoverflow.com/a/5932203/1305768">Ryan Artecona\'s answer</a> for canvases with a variable (%) width:</p>\n\n<pre><code> HTMLCanvasElement.prototype.relMouseCoords = function (event) {\n    var totalOffsetX = 0;\n    var totalOffsetY = 0;\n    var canvasX = 0;\n    var canvasY = 0;\n    var currentElement = this;\n\n    do {\n        totalOffsetX += currentElement.offsetLeft;\n        totalOffsetY += currentElement.offsetTop;\n    }\n    while (currentElement = currentElement.offsetParent)\n\n    canvasX = event.pageX - totalOffsetX;\n    canvasY = event.pageY - totalOffsetY;\n\n    // Fix for variable canvas width\n    canvasX = Math.round( canvasX * (this.width / this.offsetWidth) );\n    canvasY = Math.round( canvasY * (this.height / this.offsetHeight) );\n\n    return {x:canvasX, y:canvasY}\n}\n</code></pre>\n'}, {'answer_id': 12114213, 'author': 'mafafu', 'author_id': 1296226, 'author_profile': 'https://Stackoverflow.com/users/1296226', 'pm_score': 5, 'selected': False, 'text': "<p>Modern browser's now handle this for you. Chrome, IE9, and Firefox support the offsetX/Y like this, passing in the event from the click handler.</p>\n\n<pre><code>function getRelativeCoords(event) {\n    return { x: event.offsetX, y: event.offsetY };\n}\n</code></pre>\n\n<p>Most modern browsers also support layerX/Y, however Chrome and IE use layerX/Y for  the absolute offset of the click on the page including margin, padding, etc. In Firefox, layerX/Y and offsetX/Y are equivalent, but offset didn't previously exist. So, for compatibility with slightly older browsers, you can use:</p>\n\n<pre><code>function getRelativeCoords(event) {\n    return { x: event.offsetX || event.layerX, y: event.offsetY || event.layerY };\n}\n</code></pre>\n"}, {'answer_id': 17178241, 'author': 'Simon Hi', 'author_id': 2458202, 'author_profile': 'https://Stackoverflow.com/users/2458202', 'pm_score': 0, 'selected': False, 'text': '<p>Here is some modifications of the above Ryan Artecona\'s solution.</p>\n\n<pre><code>function myGetPxStyle(e,p)\n{\n    var r=window.getComputedStyle?window.getComputedStyle(e,null)[p]:"";\n    return parseFloat(r);\n}\n\nfunction myGetClick=function(ev)\n{\n    // {x:ev.layerX,y:ev.layerY} doesn\'t work when zooming with mac chrome 27\n    // {x:ev.clientX,y:ev.clientY} not supported by mac firefox 21\n    // document.body.scrollLeft and document.body.scrollTop seem required when scrolling on iPad\n    // html is not an offsetParent of body but can have non null offsetX or offsetY (case of wordpress 3.5.1 admin pages for instance)\n    // html.offsetX and html.offsetY don\'t work with mac firefox 21\n\n    var offsetX=0,offsetY=0,e=this,x,y;\n    var htmls=document.getElementsByTagName("html"),html=(htmls?htmls[0]:0);\n\n    do\n    {\n        offsetX+=e.offsetLeft-e.scrollLeft;\n        offsetY+=e.offsetTop-e.scrollTop;\n    } while (e=e.offsetParent);\n\n    if (html)\n    {\n        offsetX+=myGetPxStyle(html,"marginLeft");\n        offsetY+=myGetPxStyle(html,"marginTop");\n    }\n\n    x=ev.pageX-offsetX-document.body.scrollLeft;\n    y=ev.pageY-offsetY-document.body.scrollTop;\n    return {x:x,y:y};\n}\n</code></pre>\n'}, {'answer_id': 17401918, 'author': 'FraZer', 'author_id': 2515750, 'author_profile': 'https://Stackoverflow.com/users/2515750', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a very nice tutorial-</p>\n\n<p><a href="http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/" rel="noreferrer">http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/</a></p>\n\n<pre><code> &lt;canvas id="myCanvas" width="578" height="200"&gt;&lt;/canvas&gt;\n&lt;script&gt;\n  function writeMessage(canvas, message) {\n    var context = canvas.getContext(\'2d\');\n    context.clearRect(0, 0, canvas.width, canvas.height);\n    context.font = \'18pt Calibri\';\n    context.fillStyle = \'black\';\n    context.fillText(message, 10, 25);\n  }\n  function getMousePos(canvas, evt) {\n    var rect = canvas.getBoundingClientRect();\n    return {\n      x: evt.clientX - rect.left,\n      y: evt.clientY - rect.top\n    };\n  }\n  var canvas = document.getElementById(\'myCanvas\');\n  var context = canvas.getContext(\'2d\');\n\n  canvas.addEventListener(\'mousemove\', function(evt) {\n    var mousePos = getMousePos(canvas, evt);\n    var message = \'Mouse position: \' + mousePos.x + \',\' + mousePos.y;\n    writeMessage(canvas, message);\n  }, false);\n</code></pre>\n\n<p>hope this helps!</p>\n'}, {'answer_id': 17418121, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I recommend this link-\n<a href="http://miloq.blogspot.in/2011/05/coordinates-mouse-click-canvas.html" rel="nofollow">http://miloq.blogspot.in/2011/05/coordinates-mouse-click-canvas.html</a></p>\n\n<p></p>\n\n<pre><code>&lt;style type="text/css"&gt;\n\n  #canvas{background-color: #000;}\n\n&lt;/style&gt;\n\n&lt;script type="text/javascript"&gt;\n\n  document.addEventListener("DOMContentLoaded", init, false);\n\n  function init()\n  {\n    var canvas = document.getElementById("canvas");\n    canvas.addEventListener("mousedown", getPosition, false);\n  }\n\n  function getPosition(event)\n  {\n    var x = new Number();\n    var y = new Number();\n    var canvas = document.getElementById("canvas");\n\n    if (event.x != undefined &amp;&amp; event.y != undefined)\n    {\n      x = event.x;\n      y = event.y;\n    }\n    else // Firefox method to get the position\n    {\n      x = event.clientX + document.body.scrollLeft +\n          document.documentElement.scrollLeft;\n      y = event.clientY + document.body.scrollTop +\n          document.documentElement.scrollTop;\n    }\n\n    x -= canvas.offsetLeft;\n    y -= canvas.offsetTop;\n\n    alert("x: " + x + "  y: " + y);\n  }\n\n&lt;/script&gt;\n</code></pre>\n'}, {'answer_id': 18053642, 'author': 'patriques', 'author_id': 931738, 'author_profile': 'https://Stackoverflow.com/users/931738', 'pm_score': 9, 'selected': True, 'text': '<p>If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but <strong>without jQuery</strong>.</p>\n\n<pre><code>function getCursorPosition(canvas, event) {\n    const rect = canvas.getBoundingClientRect()\n    const x = event.clientX - rect.left\n    const y = event.clientY - rect.top\n    console.log("x: " + x + " y: " + y)\n}\n\nconst canvas = document.querySelector(\'canvas\')\ncanvas.addEventListener(\'mousedown\', function(e) {\n    getCursorPosition(canvas, e)\n})\n</code></pre>\n'}, {'answer_id': 19740807, 'author': 'user2310569', 'author_id': 2310569, 'author_profile': 'https://Stackoverflow.com/users/2310569', 'pm_score': 1, 'selected': False, 'text': '<p>You could just do: </p>\n\n<pre><code>var canvas = yourCanvasElement;\nvar mouseX = (event.clientX - (canvas.offsetLeft - canvas.scrollLeft)) - 2;\nvar mouseY = (event.clientY - (canvas.offsetTop - canvas.scrollTop)) - 2;\n</code></pre>\n\n<p>This will give you the exact position of the mouse pointer.</p>\n'}, {'answer_id': 20310070, 'author': 'Daniel Patru', 'author_id': 268040, 'author_profile': 'https://Stackoverflow.com/users/268040', 'pm_score': 1, 'selected': False, 'text': '<p>See demo at <a href="http://jsbin.com/ApuJOSA/1/edit?html,output" rel="nofollow">http://jsbin.com/ApuJOSA/1/edit?html,output</a> .</p>\n\n<pre><code>  function mousePositionOnCanvas(e) {\n      var el=e.target, c=el;\n      var scaleX = c.width/c.offsetWidth || 1;\n      var scaleY = c.height/c.offsetHeight || 1;\n\n      if (!isNaN(e.offsetX)) \n          return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };\n\n      var x=e.pageX, y=e.pageY;\n      do {\n        x -= el.offsetLeft;\n        y -= el.offsetTop;\n        el = el.offsetParent;\n      } while (el);\n      return { x: x*scaleX, y: y*scaleY };\n  }\n</code></pre>\n'}, {'answer_id': 20930829, 'author': 'Wayne', 'author_id': 592746, 'author_profile': 'https://Stackoverflow.com/users/592746', 'pm_score': 0, 'selected': False, 'text': '<p>First, as others have said, you need a function to get the <a href="http://www.quirksmode.org/js/findpos.html" rel="nofollow">position of the canvas element</a>. Here\'s a method that\'s a little more elegant than some of the others on this page (IMHO). You can pass it <em>any</em> element and get its position in the document:</p>\n\n<pre><code>function findPos(obj) {\n    var curleft = 0, curtop = 0;\n    if (obj.offsetParent) {\n        do {\n            curleft += obj.offsetLeft;\n            curtop += obj.offsetTop;\n        } while (obj = obj.offsetParent);\n        return { x: curleft, y: curtop };\n    }\n    return undefined;\n}\n</code></pre>\n\n<p>Now calculate the current position of the cursor relative to that:</p>\n\n<pre><code>$(\'#canvas\').mousemove(function(e) {\n    var pos = findPos(this);\n    var x = e.pageX - pos.x;\n    var y = e.pageY - pos.y;\n    var coordinateDisplay = "x=" + x + ", y=" + y;\n    writeCoordinateDisplay(coordinateDisplay);\n});\n</code></pre>\n\n<p>Notice that I\'ve separated the generic <code>findPos</code> function from the event handling code. (<em>As it should be</em>. We should try to keep our functions to one task each.)</p>\n\n<p>The values of <code>offsetLeft</code> and <code>offsetTop</code> are relative to <code>offsetParent</code>, which could be some wrapper <code>div</code> node (or anything else, for that matter). When there is no element wrapping the <code>canvas</code> they\'re relative to the <code>body</code>, so there is no offset to subtract. This is why we need to determine the position of the canvas before we can do anything else.</p>\n\n<p>Similary, <code>e.pageX</code> and <code>e.pageY</code> give the position of the cursor relative to the document. That\'s why we subtract the canvas\'s offset from those values to arrive at the true position.</p>\n\n<p>An alternative for <em>positioned</em> elements is to directly use the values of <code>e.layerX</code> and <code>e.layerY</code>. This is less reliable than the method above for two reasons:</p>\n\n<ol>\n<li>These values are also relative to the entire document when the event does not take place inside a positioned element</li>\n<li>They are not part of any standard</li>\n</ol>\n'}, {'answer_id': 27204937, 'author': 'Tomáš Zato', 'author_id': 607407, 'author_profile': 'https://Stackoverflow.com/users/607407', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m not sure what\'s the point of all these answers that <a href="https://stackoverflow.com/a/5932203/607407">loop through parent elements</a> and do all kinds of <a href="http://en.wikipedia.org/wiki/Deep_magic" rel="nofollow noreferrer">weird stuff</a>.</p>\n\n<p>The <code>HTMLElement.getBoundingClientRect</code> method is designed to to handle actual screen position of any element. This includes scrolling, so stuff like <code>scrollTop</code> is not needed:</p>\n\n<blockquote>\n  <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect" rel="nofollow noreferrer"><strong>(from MDN)</strong></a> The amount of scrolling that has been done of the viewport area (or\n  <strong>any other scrollable element</strong>) is taken into account when computing the\n  bounding rectangle</p>\n</blockquote>\n\n<h3>Normal image</h3>\n\n<p>The <a href="https://stackoverflow.com/a/20788872/607407">very simplest approach</a> was already posted here. This is correct as long as <em>no wild CSS</em> rules are involved.</p>\n\n<h3>Handling stretched canvas/image</h3>\n\n<p>When image pixel width isn\'t matched by it\'s CSS width, you\'ll need to apply some ratio on pixel values:</p>\n\n<pre><code>/* Returns pixel coordinates according to the pixel that\'s under the mouse cursor**/\nHTMLCanvasElement.prototype.relativeCoords = function(event) {\n  var x,y;\n  //This is the current screen rectangle of canvas\n  var rect = this.getBoundingClientRect();\n  var top = rect.top;\n  var bottom = rect.bottom;\n  var left = rect.left;\n  var right = rect.right;\n  //Recalculate mouse offsets to relative offsets\n  x = event.clientX - left;\n  y = event.clientY - top;\n  //Also recalculate offsets of canvas is stretched\n  var width = right - left;\n  //I use this to reduce number of calculations for images that have normal size \n  if(this.width!=width) {\n    var height = bottom - top;\n    //changes coordinates by ratio\n    x = x*(this.width/width);\n    y = y*(this.height/height);\n  } \n  //Return as an array\n  return [x,y];\n}\n</code></pre>\n\n<p>As long as the canvas has no border, <a href="http://jsfiddle.net/Darker/cfzn01c6/" rel="nofollow noreferrer"><strong>it works for stretched images (jsFiddle)</strong></a>.</p>\n\n<h3>Handling CSS borders</h3>\n\n<p>If the canvas has thick border, <a href="http://jsfiddle.net/Darker/nrw7xu2r/1/" rel="nofollow noreferrer">the things get little complicated</a>. You\'ll literally need to subtract the border from the bounding rectangle. This can be done using <a href="https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle" rel="nofollow noreferrer">.getComputedStyle</a>. This <a href="https://stackoverflow.com/a/27204448/607407">answer describes the process</a>.</p>\n\n<p>The function then grows up a little:</p>\n\n<pre><code>/* Returns pixel coordinates according to the pixel that\'s under the mouse cursor**/\nHTMLCanvasElement.prototype.relativeCoords = function(event) {\n  var x,y;\n  //This is the current screen rectangle of canvas\n  var rect = this.getBoundingClientRect();\n  var top = rect.top;\n  var bottom = rect.bottom;\n  var left = rect.left;\n  var right = rect.right;\n  //Subtract border size\n  // Get computed style\n  var styling=getComputedStyle(this,null);\n  // Turn the border widths in integers\n  var topBorder=parseInt(styling.getPropertyValue(\'border-top-width\'),10);\n  var rightBorder=parseInt(styling.getPropertyValue(\'border-right-width\'),10);\n  var bottomBorder=parseInt(styling.getPropertyValue(\'border-bottom-width\'),10);\n  var leftBorder=parseInt(styling.getPropertyValue(\'border-left-width\'),10);\n  //Subtract border from rectangle\n  left+=leftBorder;\n  right-=rightBorder;\n  top+=topBorder;\n  bottom-=bottomBorder;\n  //Proceed as usual\n  ...\n}\n</code></pre>\n\n<p>I can\'t think of anything that would confuse this final function. See yourself at <a href="http://jsfiddle.net/Darker/nrw7xu2r/2/" rel="nofollow noreferrer"><strong>JsFiddle</strong></a>.</p>\n\n<h3>Notes</h3>\n\n<p>If you don\'t like modifying the native <code>prototype</code>s, just change the function and call it with <code>(canvas, event)</code> (and replace any <code>this</code> with <code>canvas</code>).</p>\n'}, {'answer_id': 34781170, 'author': 'Sarsaparilla', 'author_id': 226844, 'author_profile': 'https://Stackoverflow.com/users/226844', 'pm_score': 2, 'selected': False, 'text': '<p>Using jQuery in 2016, to get click coordinates relative to the canvas, I do:</p>\n\n<pre><code>$(canvas).click(function(jqEvent) {\n    var coords = {\n        x: jqEvent.pageX - $(canvas).offset().left,\n        y: jqEvent.pageY - $(canvas).offset().top\n    };\n});\n</code></pre>\n\n<p>This works since both canvas offset() and jqEvent.pageX/Y are relative to the document regardless of scroll position.</p>\n\n<p>Note that if your canvas is scaled then these coordinates are not the same as canvas <strong>logical coordinates</strong>.  To get those, you would <em>also</em> do:</p>\n\n<pre><code>var logicalCoords = {\n    x: coords.x * (canvas.width / $(canvas).width()),\n    y: coords.y * (canvas.height / $(canvas).height())\n}\n</code></pre>\n'}, {'answer_id': 37790303, 'author': 'Aniket Betkikar', 'author_id': 5275732, 'author_profile': 'https://Stackoverflow.com/users/5275732', 'pm_score': 0, 'selected': False, 'text': '<p>ThreeJS r77</p>\n\n<pre><code>var x = event.offsetX == undefined ? event.layerX : event.offsetX;\nvar y = event.offsetY == undefined ? event.layerY : event.offsetY;\n\nmouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;\nmouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;\n</code></pre>\n\n<p>After trying many solutions. This worked for me. Might help someone else hence posting. Got it from <a href="http://www.scriptscoop2.com/t/f93cbd2d95e2/javascript-threejs-issue-with-raycaster-intersection.html" rel="nofollow">here</a></p>\n'}, {'answer_id': 54356770, 'author': 'bb216b3acfd8f72cbc8f899d4d6963', 'author_id': 5513988, 'author_profile': 'https://Stackoverflow.com/users/5513988', 'pm_score': 0, 'selected': False, 'text': "<p>Here is a simplified solution (this doesn't work with borders/scrolling):</p>\n\n<pre><code>function click(event) {\n    const bound = event.target.getBoundingClientRect();\n\n    const xMult = bound.width / can.width;\n    const yMult = bound.height / can.height;\n\n    return {\n        x: Math.floor(event.offsetX / xMult),\n        y: Math.floor(event.offsetY / yMult),\n    };\n}\n</code></pre>\n"}, {'answer_id': 56205486, 'author': 'gman', 'author_id': 128511, 'author_profile': 'https://Stackoverflow.com/users/128511', 'pm_score': 4, 'selected': False, 'text': '<p>So this is both simple but a slightly more complicated topic than it seems.</p>\n<p>First off there are usually to conflated questions here</p>\n<ol>\n<li><p><strong>How to get element relative mouse coordinates</strong></p>\n</li>\n<li><p><strong>How to get canvas pixel mouse coordinates for the 2D Canvas API or WebGL</strong></p>\n</li>\n</ol>\n<p>so, answers</p>\n<h1>How to get element relative mouse coordinates</h1>\n<p>Whether or not the element is a canvas getting element relative mouse coordinates is the same for all elements.</p>\n<p>There are 2 simple answers to the question &quot;How to get canvas relative mouse coordinates&quot;</p>\n<h3>Simple answer #1 use <code>offsetX</code> and <code>offsetY</code></h3>\n<pre><code>canvas.addEventListner(\'mousemove\', (e) =&gt; {\n  const x = e.offsetX;\n  const y = e.offsetY;\n});\n</code></pre>\n<p>This answer works in Chrome, Firefox, and Safari. Unlike all the other event values <code>offsetX</code> and <code>offsetY</code> take CSS transforms into account.</p>\n<p>The biggest problem with <code>offsetX</code> and <code>offsetY</code> is as of 2019/05 they don\'t exist on touch events and so can\'t be used with iOS Safari. They do exist on Pointer Events which exist in Chrome and Firefox but not Safari although <a href="https://webkit.org/blog/8419/release-notes-for-safari-technology-preview-67/" rel="noreferrer">apparently Safari is working on it</a>.</p>\n<p>Another issue is the events must be on the canvas itself. If you put them on some other element or the window you can not later choose the canvas to be your point of reference.</p>\n<h2>Simple answer #2 use <code>clientX</code>, <code>clientY</code> and <code>canvas.getBoundingClientRect</code></h2>\n<p>If you don\'t care about CSS transforms the next simplest answer is to call <code>canvas. getBoundingClientRect()</code> and subtract the left from <code>clientX</code> and <code>top</code> from <code>clientY</code> as in</p>\n<pre><code>canvas.addEventListener(\'mousemove\', (e) =&gt; {\n  const rect = canvas.getBoundingClientRect();\n  const x = e.clientX - rect.left;\n  const y = e.clientY - rect.top;\n});\n</code></pre>\n<p>This will work as long as there are no CSS transforms. It also works with touch events and so will work with Safari iOS</p>\n<pre><code>canvas.addEventListener(\'touchmove\', (e) =&gt; {\n  const rect = canvas. getBoundingClientRect();\n  const x = e.touches[0].clientX - rect.left;\n  const y = e.touches[0].clientY - rect.top;\n});\n</code></pre>\n<h1>How to get canvas pixel mouse coordinates for the 2D Canvas API</h1>\n<p>For this we need to take the values we got above and convert from the size the canvas is displayed to the number of pixels in the canvas itself</p>\n<p>with <code>canvas.getBoundingClientRect</code> and <code>clientX</code> and <code>clientY</code></p>\n<pre><code>canvas.addEventListener(\'mousemove\', (e) =&gt; {\n  const rect = canvas.getBoundingClientRect();\n  const elementRelativeX = e.clientX - rect.left;\n  const elementRelativeY = e.clientY - rect.top;\n  const canvasRelativeX = elementRelativeX * canvas.width / rect.width;\n  const canvasRelativeY = elementRelativeY * canvas.height / rect.height;\n});\n</code></pre>\n<p>or with <code>offsetX</code> and <code>offsetY</code></p>\n<pre><code>canvas.addEventListener(\'mousemove\', (e) =&gt; {\n  const elementRelativeX = e.offsetX;\n  const elementRelativeY = e.offsetY;\n  const canvasRelativeX = elementRelativeX * canvas.width / canvas.clientWidth;\n  const canvasRelativeY = elementRelativeY * canvas.height / canvas.clientHeight;\n});\n</code></pre>\n<h1>Note: <strong>In all cases do not add padding or borders to the canvas. Doing so will massively complicate the code. Instead of you want a border or padding surround the canvas in some other element and add the padding and or border to the outer element.</strong></h1>\n<p>Working example using <code>event.offsetX</code>, <code>event.offsetY</code></p>\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>[...document.querySelectorAll(\'canvas\')].forEach((canvas) =&gt; {\n  const ctx = canvas.getContext(\'2d\');\n  ctx.canvas.width  = ctx.canvas.clientWidth;\n  ctx.canvas.height = ctx.canvas.clientHeight;\n  let count = 0;\n\n  function draw(e, radius = 1) {\n    const pos = {\n      x: e.offsetX * canvas.width  / canvas.clientWidth,\n      y: e.offsetY * canvas.height / canvas.clientHeight,\n    };\n    document.querySelector(\'#debug\').textContent = count;\n    ctx.beginPath();\n    ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);\n    ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);\n    ctx.fill();\n  }\n\n  function preventDefault(e) {\n    e.preventDefault();\n  }\n\n  if (window.PointerEvent) {\n    canvas.addEventListener(\'pointermove\', (e) =&gt; {\n      draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));\n    });\n    canvas.addEventListener(\'touchstart\', preventDefault, {passive: false});\n    canvas.addEventListener(\'touchmove\', preventDefault, {passive: false});\n  } else {\n    canvas.addEventListener(\'mousemove\', draw);\n    canvas.addEventListener(\'mousedown\', preventDefault);\n  }\n});\n\nfunction hsl(h, s, l) {\n  return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;\n}</code></pre>\r\n<pre class="snippet-code-css lang-css prettyprint-override"><code>.scene {\n  width: 200px;\n  height: 200px;\n  perspective: 600px;\n}\n\n.cube {\n  width: 100%;\n  height: 100%;\n  position: relative;\n  transform-style: preserve-3d;\n  animation-duration: 16s;\n  animation-name: rotate;\n  animation-iteration-count: infinite;\n  animation-timing-function: linear;\n}\n\n@keyframes rotate {\n  from { transform: translateZ(-100px) rotateX(  0deg) rotateY(  0deg); }\n  to   { transform: translateZ(-100px) rotateX(360deg) rotateY(720deg); }\n}\n\n.cube__face {\n  position: absolute;\n  width: 200px;\n  height: 200px;\n  display: block;\n}\n\n.cube__face--front  { background: rgba(255, 0, 0, 0.2); transform: rotateY(  0deg) translateZ(100px); }\n.cube__face--right  { background: rgba(0, 255, 0, 0.2); transform: rotateY( 90deg) translateZ(100px); }\n.cube__face--back   { background: rgba(0, 0, 255, 0.2); transform: rotateY(180deg) translateZ(100px); }\n.cube__face--left   { background: rgba(255, 255, 0, 0.2); transform: rotateY(-90deg) translateZ(100px); }\n.cube__face--top    { background: rgba(0, 255, 255, 0.2); transform: rotateX( 90deg) translateZ(100px); }\n.cube__face--bottom { background: rgba(255, 0, 255, 0.2); transform: rotateX(-90deg) translateZ(100px); }</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="scene"&gt;\n  &lt;div class="cube"&gt;\n    &lt;canvas class="cube__face cube__face--front"&gt;&lt;/canvas&gt;\n    &lt;canvas class="cube__face cube__face--back"&gt;&lt;/canvas&gt;\n    &lt;canvas class="cube__face cube__face--right"&gt;&lt;/canvas&gt;\n    &lt;canvas class="cube__face cube__face--left"&gt;&lt;/canvas&gt;\n    &lt;canvas class="cube__face cube__face--top"&gt;&lt;/canvas&gt;\n    &lt;canvas class="cube__face cube__face--bottom"&gt;&lt;/canvas&gt;\n  &lt;/div&gt;\n&lt;/div&gt;\n&lt;pre id="debug"&gt;&lt;/pre&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Working example using <code>canvas.getBoundingClientRect</code> and <code>event.clientX</code> and <code>event.clientY</code></p>\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const canvas = document.querySelector(\'canvas\');\nconst ctx = canvas.getContext(\'2d\');\nctx.canvas.width  = ctx.canvas.clientWidth;\nctx.canvas.height = ctx.canvas.clientHeight;\nlet count = 0;\n\nfunction draw(e, radius = 1) {\n  const rect = canvas.getBoundingClientRect();\n  const pos = {\n    x: (e.clientX - rect.left) * canvas.width  / canvas.clientWidth,\n    y: (e.clientY - rect.top) * canvas.height / canvas.clientHeight,\n  };\n  ctx.beginPath();\n  ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);\n  ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);\n  ctx.fill();\n}\n\nfunction preventDefault(e) {\n  e.preventDefault();\n}\n\nif (window.PointerEvent) {\n  canvas.addEventListener(\'pointermove\', (e) =&gt; {\n    draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));\n  });\n  canvas.addEventListener(\'touchstart\', preventDefault, {passive: false});\n  canvas.addEventListener(\'touchmove\', preventDefault, {passive: false});\n} else {\n  canvas.addEventListener(\'mousemove\', draw);\n  canvas.addEventListener(\'mousedown\', preventDefault);\n}\n\nfunction hsl(h, s, l) {\n  return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;\n}</code></pre>\r\n<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { background: #FED; }</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas width="400" height="100" style="width: 300px; height: 200px"&gt;&lt;/canvas&gt;\n&lt;div&gt;canvas deliberately has differnt CSS size vs drawingbuffer size&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 56363476, 'author': 'Divyanshu Rawat', 'author_id': 5763627, 'author_profile': 'https://Stackoverflow.com/users/5763627', 'pm_score': 1, 'selected': False, 'text': "<p>I was creating an application having a <strong>canvas</strong> over a pdf, that involved a lot of resizes of canvas like Zooming the pdf-in and out, and in turn on every zoom-in/out of PDF I had to resize the canvas to adapt the size of the pdf,  I went through lot of answers in stackOverflow, and didn't found a perfect solution that will eventually solve the problem.</p>\n\n<p>I was using <strong>rxjs</strong> and angular 6, and didn't found any answer specific to the newest version.</p>\n\n<p>Here is the entire code snippet that would be helpful, to anyone leveraging <strong>rxjs</strong> to draw on top of canvas.</p>\n\n<pre><code>  private captureEvents(canvasEl: HTMLCanvasElement) {\n\n    this.drawingSubscription = fromEvent(canvasEl, 'mousedown')\n      .pipe(\n        switchMap((e: any) =&gt; {\n\n          return fromEvent(canvasEl, 'mousemove')\n            .pipe(\n              takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) =&gt; {\n                const prevPos = {\n                  x: null,\n                  y: null\n                };\n              })),\n\n              takeUntil(fromEvent(canvasEl, 'mouseleave')),\n              pairwise()\n            )\n        })\n      )\n      .subscribe((res: [MouseEvent, MouseEvent]) =&gt; {\n        const rect = this.cx.canvas.getBoundingClientRect();\n        const prevPos = {\n          x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n          y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n        };\n        const currentPos = {\n          x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n          y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n        };\n\n        this.coordinatesArray[this.file.current_slide - 1].push(prevPos);\n        this.drawOnCanvas(prevPos, currentPos);\n      });\n  }\n</code></pre>\n\n<p>And here is the snippet that fixes, mouse coordinates relative to size of the canvas, irrespective of how you zoom-in/out the canvas.</p>\n\n<pre><code>const prevPos = {\n  x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n  y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n};\nconst currentPos = {\n  x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n  y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n};\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/55677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3715/']