将单击事件处理程序添加到将返回单击的x和y坐标(相对于canvas元素)的canvas元素的最简单方法是什么?
不需要传统的浏览器兼容性,Safari,Opera和Firefox都可以.
我想将画布鼠标坐标传递给一个以鼠标坐标为中心交互式生成圆形的函数.因此,我正在使用以下函数进行规范化:
var mousePositionX = (2*ev.clientX/canvas.width) - 1;
var mousePositionY = (2*ev.clientY/(canvas.height*-1)) + 1;
Run Code Online (Sandbox Code Playgroud)
但是,这仅适用于屏幕中心.当移动鼠标时,光标不再位于圆圈的中心: 请参见此处的图片
鼠标光标从屏幕中心移开的距离越远,它与圆圈中心的距离就越大.这是一些相关的代码:
HTML
body {
border: 0;
margin: 0;
}
/* make the canvas the size of the viewport */
canvas {
width: 100vw;
height: 100vh;
display: block;
}
...
<body onLoad="main()">
<canvas id="glContext"></canvas>
</body>
Run Code Online (Sandbox Code Playgroud)
SHADER
<script id="vShaderCircle" type="notjs">
attribute vec4 a_position;
uniform mat4 u_viewMatrix;
void main(){
gl_Position = u_viewMatrix * a_position;
}
</script>
Run Code Online (Sandbox Code Playgroud)
JS
function main(){
// PREPARING CANVAS AND WEBGL-CONTEXT
var canvas = document.getElementById("glContext"); …Run Code Online (Sandbox Code Playgroud)