在divis

时间:2017-07-18 09:13:52

标签: javascript html css canvas

我在两个div标签内有画布。我试图用画布在画布上画画,但我无法从精确的鼠标指针位置开始这里是代码 CSS

div.ot_whiteboard
 {
 display: block;
 background-color: #DCD9CD;
 margin: 0 auto;
 padding: 10px;
 position: relative;
 }
canvas.canvas_test{
 height:100%;
 width:100%;
position:relative;
    }

JS

var mainCanvas =document.getElementById('canvas_test');
 var previousMousePos,mousePos,paint=false;


  mainCanvas.addEventListener("mousemove",draw,false);
  mainCanvas.addEventListener("mousedown",startdraw,false);
  mainCanvas.addEventListener("mouseup",stopdraw,false);

 function startdraw(event){
  paint=true;
 previousMousePos = getMousePos(event);
 }
function draw(event){
if(paint){
 mousePos = getMousePos(event);
var mainCanvas = document.getElementById('canvas_test');
var ctx = mainCanvas.getContext('2d');
 console.log(" X position :"+ previousMousePos.x);
  console.log(" X position :"+ mousePos.x);
 console.log(" Y position :"+ previousMousePos.y);
 console.log(" Y position :"+ mousePos.y);
 ctx.strokeStyle = "black";
       ctx.lineWidth = 2;
       ctx.beginPath();
       ctx.moveTo(previousMousePos.x, previousMousePos.y);
       ctx.lineTo(mousePos.x, mousePos.y);
       ctx.stroke();
       ctx.closePath();
   previousMousePos = mousePos;
 }
}
function stopdraw(event){
  paint=false;
 previousMousePos = getMousePos(event);
 }

function getMousePos(evt) {
                var obj=document.getElementById("canvas_test");
        var top = 0;
        var left = 0;
        while (obj) {
            top += obj.offsetTop;
            left += obj.offsetLeft;
            obj = obj.offsetParent;
        }
        // return relative mouse position
        var mouseX = evt.clientX - left + this.pageXOffset;
        var mouseY = evt.clientY - top + this.pageYOffset;
        return {
            x:mouseX,
            y:mouseY
        };
    }

HTML

<div style="width:800px;height:520px;border:1px solid black;position: relative;" >
 <div class="ot_whiteboard" style="width:500px;height:500px;align:center;">
 <canvas id="canvas_test" class="canvas_test"></canvas>
</div>

你能不能帮助我获得鼠标指针的确切指针

1 个答案:

答案 0 :(得分:1)

您需要缩放鼠标坐标以匹配画布分辨率。

// your code
var mouseX = evt.clientX - left + window.pageXOffset;
var mouseY = evt.clientY - top + window.pageYOffset;

// Add the following 3 lines to scale the mouse coordinates to the
// canvas resolution
const bounds = canvas_test.getBoundingClientRect();
mouseX = (mouseX / bounds.width) * canvas_test.width;
mouseY = (mouseY / bounds.height) * canvas_test.height;

// your code
return {
    x:mouseX,
    y:mouseY
};