[英]How do I confine object creation to the canvas?
http://jsfiddle.net/goldrunt/SeAGU/33/ Lines 24-40 are meant to limit circle creation to the canvas. http://jsfiddle.net/goldrunt/SeAGU/33/第24至40行旨在将圆的创建限制在画布上。 I need to check the location before allowing the new object to be created. 在允许创建新对象之前,我需要检查位置。 How would I do this if the object doesn't exist yet? 如果对象尚不存在,该怎么办?
function isAtWall(a) {
return (a.x - a.radius <= rect.left || a.y + a.radius >= rect.top || a.x + a.radius >= rect.left + canvas.width || a.y - a.radius <= rect.top - canvas.height);
}
window.onmousedown = function (e) {
// IE fixer
e = e || window.event;
// get event location on page offset by canvas location
var location = {
x: e.pageX - offset.x,
y: e.pageY - offset.y
};
if (!isAtWall(location)) {
create(location);
}
};
Make it simpler to start off with and you'll get to the answer much easier: 让它从一开始就更简单,您将轻松获得答案:
function isAtWall(a) {
if ((a.x >= 0 && a.x <= rect.width) && (a.y >= 0 && a.y <= rect.height))
{
return false;
}
return true;
}
http://jsfiddle.net/SeAGU/35/ http://jsfiddle.net/SeAGU/35/
That will only allow the user to place circles on the canvas. 那将仅允许用户在画布上放置圆圈。
EDIT: Just to clarify, I'm deliberately leaving out the circle radius calculation. 编辑:只是为了澄清,我故意省略了圆半径的计算。 This function will only determine if the click event is on the canvas. 此函数将仅确定click事件是否在画布上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.