我花了一整天的时间试图点击我的画布以返回像素 xy 偏移量.这是一项多么艰巨的任务!
这就是我最终得到的结果:
<!DOCTYPE html><html><头><meta charset="utf-8"><title>JS斌</title></头><身体><script src="https://code.jquery.com/jquery-1.10.2.js"></script><div id="logX">x</div><div id="logY">y</div><div style="margin-left:100px"><div style="margin-left:100px"><canvas id="myCanvas" width="100" height="1000" style="border:20px solid #000000;"></canvas></div></div><脚本>var canvas = document.getElementById('myCanvas');canvas.addEventListener('click', on_canvas_click, false);函数getNumericStyleProperty(样式,道具){返回 parseInt(style.getPropertyValue(prop),10);}功能 on_canvas_click(ev) {var boundingRect = ev.target.getBoundingClientRect();var x = ev.clientX - boundingRect.left,y = ev.clientY - boundingRect.top;var style = getComputedStyle(canvas, null);x -= getNumericStyleProperty(style, "margin-left");y -= getNumericStyleProperty(style, "margin-top");x -= getNumericStyleProperty(style, "border-left-width");y -= getNumericStyleProperty(style, "border-top-width");x -= getNumericStyleProperty(style, "padding-left");y -= getNumericStyleProperty(style, "padding-top");$("#logX").text(ev.target.getBoundingClientRect().left+ ", " + ev.clientX+ ", " + canvas.offsetLeft+ ", " + x);$("#logY").text(ev.target.getBoundingClientRect().top+ ", " + ev.clientY+ ", " + canvas.offsetTop+ ", " + y);}//$( document ).on( "mousemove", function( event ) {//$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );/