我需要在画布上单击特定(点)或矩形的onclick动作。
例:
$(document).ready(function(){
var canvas = $('#myCanvas').get(0);
if (!canvas.getContext) { return; }
var ctx = canvas.getContext('2d');
ctx.fillRect(150,140,8,8);
ctx.fillRect(200,120,8,8);
ctx.fillRect(200,160,8,8);
});
我需要使用javascript连接两条直线和一条曲线连接另外两个点。我该怎么做?
最佳答案
您需要自己维护区域。画布上没有对象,只有像素,浏览器对此一无所知。
Demo here
您可以执行以下操作(简化):
// define the regions - common for draw/redraw and check
var rect1 = [150,140,8,8];
var rect2 = [200,120,8,8];
var rect3 = [200,160,8,8];
var regions = [rect1, rect2, rect3];
现在在您的init上,您可以使用相同的数组来渲染所有矩形:
$(document).ready(function(){
var canvas = $('#myCanvas').get(0);
if (!canvas.getContext) { return; }
var ctx = canvas.getContext('2d');
//use the array also to render the boxes
for (var i = 0, r; r = regions[i]; i++) {
ctx.fillRect(r[0],r[1],r[2],r[3]);
}
});
在click事件上,您检查数组以查看鼠标坐标(针对画布进行了校正)是否在任何矩形内:
$('#myCanvas').on('click', function(e){
var pos = getMousePos(this, e);
// check if we got a hit
for (var i = 0, r; r = regions[i]; i++) {
if (pos.x >= r[0] && pos.x <= (r[0] + r[2]) &&
pos.y >= r[1] && pos.y <= (r[1] + r[3])) {
alert('Region ' + i + ' was hit');
}
}
});
//get mouse position relative to canvas
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
还请记住,如果调整窗口大小或由于其他原因清除了画布(浏览器对话框等),请重新绘制画布。
要连接盒子,您需要存储第一个命中位置,当您获得第二个命中位置时,请在它们之间画一条线。
Demo with lines here
添加到全局变量中,还可以从全局变量中获取画布和上下文(有关准备就绪的相关修改,请参见小提琴):
var x1 = -1, y1;
var canvas = myCanvas;
var ctx = canvas.getContext('2d');
在点击事件中:
$('#myCanvas').on('click', function(e){
var pos = getMousePos(this, e);
for (var i = 0, r; r = regions[i]; i++) {
if (pos.x >= r[0] && pos.x <= (r[0] + r[2]) &&
pos.y >= r[1] && pos.y <= (r[1] + r[3])) {
//first hit? then store the coords
if (x1 === -1) {
x1 = pos.x;
y1 = pos.y;
} else {
//draw line from first point to this
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
x1 = -1; //reset (or keep if you want continuous lines).
};
}
}
});
关于javascript - 基于对象的Canvas JavaScript事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17403083/