-1

我正在创建一个canvas基于“选择您自己的座位”的预订系统,并且难以确定如何确定是否已点击其中一个圆圈。座位是基于从一个填充了从CRM system. 我曾尝试使用“this”关键字,并认为这会有所帮助。我想我可以使用坐标来确定选择了哪个座位,然后返回该座位的 ID,以便通过 CRM 请求预订。

我应该创建一个多维数组并用坐标和座位 ID 填充它吗?

    document.addEventListener('DOMContentLoaded',domloaded,false);
    function domloaded(){
    var canvas = document.getElementById("mycanvas");
    var ctx = canvas.getContext("2d");
    var allseats = document.getElementsByClassName("seat");
    var arr = Array.prototype.slice.call(allseats); 

        for (var j=0; j<arr.length; j++)
       {
    //Get seat status
    var status = arr[j].getAttribute("data-seat-status");
    //Get row position
    var top = arr[j].getAttribute("data-top");
    //Get column position
    var left = arr[j].getAttribute("data-left");
    //Get seat id
    var id = arr[j].getAttribute("id");

    var sAngle = 0;
    var eAngle = 2*Math.PI;

    //Create more space between seats
    left=(left*10);
    top=(top*10);

     var seat = function(){
     function seat(x, y) {
        this.color = "white";
        this.x = left;
        this.y = top;
        this.radius = 4;
    }
        seat.prototype.draw = function (ctx) {
        ctx.fillStyle = "red";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
        ctx.fill();
    };
        return seat;
    }();
    var drawSeats=new seat(top,left);
    drawSeats.draw(ctx);    

    }
    canvas.onmousedown=function findseats(arr){


  var xleft=arr.clientX;
  var ytop=arr.clientY;
  alert("X coords: " + xleft + ", Y coords: " + ytop);
    for (s=0; s<arr.length; s++){
        if((xleft||((arr[s].getAttribute("data-left")*10)&&(ytop||arr[s].getAttribute("data-top")*10)))){
            alert(arr[s].getAttribute("data-id"));
        }

    }
    }}

http://jsfiddle.net/caspianturner/5sycT

4

1 回答 1

0

演示:http: //jsfiddle.net/m1erickson/AN4Jf/

您可以监听 mousedown 事件并在事件发生时调用 handleMouseDown():

canvas.onmousedown=handleMouseDown;

mousedown 处理程序获取鼠标位置,如下所示:

var canvas=document.getElementById("canvas");
var offsetX=canvas.offsetLeft;
var offsetY=canvas.offsetTop;

function handleMouseDown(e){
    e.preventDefault();

    mouseX=parseInt(e.clientX-offsetX);

    mouseY=parseInt(e.clientY-offsetY);


}

假设您的座位“类”看起来像这样:

// Seat "class"
function Seat(x,y,radius,id,seatNo,color){
    this.x=x-200;  // -200 pulls the seats leftward for better display
    this.y=y;
    this.radius=radius;
    this.id=id;
    this.seatNo=seatNo;
    this.color=color
}

然后您可以测试 mousedown 是否发生在任何 Seat 对象中,如下所示:

Seat.prototype.isMouseInside=function(mouseX,mouseY){
    var dx=mouseX-this.x;
    var dy=mouseY-this.y;
    return(dx*dx+dy*dy<=this.radius*this.radius);
}
于 2014-03-15T17:51:25.610 回答