简体   繁体   English

在画布上拖动点并获取坐标

[英]dragging points in a canvas and get the coordinates

I need to drag any point inside the canvas and I need to get the coordinate it occupies. 我需要在画布内拖动任何点,并且需要获取它占用的坐标。 I am new to canvas, I do not know how to do it. 我是画布的新手,我不知道该怎么做。 I would also like to get the coordinates of all points. 我也想获得所有点的坐标。

http://jsfiddle.net/bfe8160h/ http://jsfiddle.net/bfe8160h/

在此处输入图片说明

$("#canvas").click(function(e){
     getPosition(e); 
});

var pointSize = 3;

function getPosition(event){
     var rect = canvas.getBoundingClientRect();
     var x = event.clientX - rect.left;
     var y = event.clientY - rect.top;

     drawCoordinates(x,y);
}

function drawCoordinates(x,y){  
    var ctx = document.getElementById("canvas").getContext("2d");


    ctx.fillStyle = "#ff2626"; // Red color

    ctx.beginPath();
    ctx.arc(x, y, pointSize, 0, Math.PI * 2, true);
    ctx.fill();
}

I need to get the position of the new points. 我需要获得新观点的立场。 For example if I move a point that is in (1,2) to (4,6) I need to get 4.6 when I finish moving the point 例如,如果我将(1,2)的点移动到(4,6),则在完成移动点时需要获得4.6

If you want to get the coordinates x,y when you move the cursor, add the following to your code: 如果要在移动光标时获取x,y坐标,请在代码中添加以下内容:

var allPoints = [];//contains the coordinates of all the position
var points; // contains the coordinates of the recent position

canvas = document.getElementById('canvas');

canvas.addEventListener("mousemove",function() {
    var rect = canvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    points = x+","+y;
    alert(points);
    allPoints.push(x+":"+y);//pushes the new coordinates
    alert(allPoints);
});

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

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