简体   繁体   English

html5 在 canvas 中捕获鼠标点击

[英]html5 capturing mouse clicks in a canvas

Here is simplified code that takes into account the answer suggested by nycnik.这是考虑到 nycnik 建议的答案的简化代码。 The code works better, but the scale and offset are still off.代码效果更好,但比例和偏移量仍然关闭。 Click drag and release, and the line drawn appears to be approximately a factor of 2 off.单击拖动并释放,绘制的线看起来大约是 2 倍。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="st.css" media="all"/>
    <script>
var x, y;
function getXY(canvas, e) {
    var rect = canvas.getBoundingClientRect();
    return [e.clientX - rect.left, e.clientY - rect.top];
}

function move(ca, e) {


}

function mark(ca, e) {
    [x,y] = getXY(ca, e);
}

function clickDrag(ca, e) {
    var c = ca.getContext("2d");
    var x2, y2;
    [x2,y2] = getXY(ca, e);
    c.fillStyle='#00FF80';
    c.lineStyle='#FFFF80';
    c.moveTo(x,y);
    c.lineTo(x2,y2);
    c.stroke();  
}
    </script>
  </head>
  <body>
    <div class="bg">
      <canvas id="q13g" onmousedown="mark(this,event)" onmouseup="clickDrag(this, event)">
      </canvas>
    </div>
  </body>
</html>

You just need to convert using clientX, that you saw, and the bounding rectangle, as seen below, and in this tutorial:您只需要使用您看到的 clientX 和边界矩形进行转换,如下所示,在本教程中:

function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }

http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM