我正在创建一个基于canvas
的Select Your Own Seat预订系统,并且无法确定如何确定是否已点击其中一个圈子。
席位基于从填充了CRM system
返回的XML数据的数组中拉来动态绘制。我曾尝试使用'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"));
}
}
}}
答案 0 :(得分: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);
}