簡體   English   中英

如何將對象創建限制在畫布上?

[英]How do I confine object creation to the canvas?

http://jsfiddle.net/goldrunt/SeAGU/33/第24至40行旨在將圓的創建限制在畫布上。 在允許創建新對象之前,我需要檢查位置。 如果對象尚不存在,該怎么辦?

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);
    }
};

讓它從一開始就更簡單,您將輕松獲得答案:

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/

那將僅允許用戶在畫布上放置圓圈。

編輯:只是為了澄清,我故意省略了圓半徑的計算。 此函數將僅確定click事件是否在畫布上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM