如何使用 P5js 将 DOM 元素拖入 canvas 而不会离开 canvas?

How to drag DOM element inside canvas without going out of canvas with P5js?

我想要的:

我有一个 div,我想将它移动到 canvas 左右,但将其限制为 canvas 宽度和高度

我有:

我正在使用 p5.dom.js

P5js代码:

let dragging = false;
let offsetX, offsetY, onsetX, onsetY;
let canvasWidth, canvasHeight;
let currentDragDiv;

function setup() {
    canvasWidth = windowWidth < 400 ? 400 : windowWidth;
    canvasHeight = windowHeight < 400 ? 400 : windowHeight;
    canvas = createCanvas(canvasWidth, canvasHeight)
            .mousePressed(createDiv);
}

function draw() {

    background(200);

    if(dragging){
        if(mouseX + onsetX < canvasWidth && mouseX + offsetX > 0){
            currentDragDiv.position(mouseX + offsetX, currentDragDiv.y);
        }
        if(mouseY + onsetY < canvasHeight && mouseY + offsetY > 0 ){
            currentDragDiv.position(currentDragDiv.x, mouseY + offsetY);
        } 
    }
}

function createDiv(){
    let div = createDiv("")
        .mousePressed(function(){ dragDiv(div); })
        .mouseReleased(function(){ dropDiv(div); })
        .position(mouseX, mouseY);
}

function dropDiv(){
    dragging = false;
    currentDragDiv = null;
}

function dragDiv(d){
    currentDragDiv = d;
    dragging = true;        
    offsetX = currentDragDiv.x - mouseX;
    offsetY = currentDragDiv.y - mouseY;
    onsetX = currentDragDiv.width + offsetX;
    onsetY = currentDragDiv.height + offsetY;
}

问题:

此代码运行良好,但如果用户移动鼠标太快,div 不会移动,直到 canvas 的边界发生 this 之类的事情(我将 div 快速向右拖动并移动到屏幕中间)。这个问题使变量 onsetX 和 onsetY 出错,并且根据 div 离 canvas 边界的距离而变得有点混乱。

是否可以删除此 "error" 并使 div 一直延伸到 canvas 的边界?

观察:

  1. 我删除了一些我认为这道题不需要的代码。
  2. 变量onsetX 和onsetY 是offsetX 和offsetY 的反义词,它是从鼠标位置到边界的位置,但是因为英语不是我的母语,所以我不知道如何命名变量。推荐一下就好了

在您当前的代码中,如果超出 canvas 的边界,则完全省略拖动:

if(mouseX + onsetX < canvasWidth && mouseX + offsetX > 0){
    currentDragDiv.position(mouseX + offsetX, currentDragDiv.y);
}
if (mouseY + onsetY < canvasHeight && mouseY + offsetY > 0 ){
    currentDragDiv.position(currentDragDiv.x, mouseY + offsetY);
}

相反,您必须将拖动限制在 0 到 canvasWidth 的范围内,分别为 0 到 canvasHeight。这意味着您必须 "clamp" 拖动到这个范围:

function draw() {
    let newX, newY;

    background(200);

    if(dragging){

        newX = mouseX + offsetX;

        if ( newX > canvasWidth ) {
            newX = canvasWidth - currentPostIt.width;
        } 
        if ( newX < 0 ) {
            newX = 0;
        }

        newY = mouseY + offsetY;

        if ( newY > canvasHeight ) {
          newY = canvasHeight - currentPostIt.height;
        } 
        if ( newY < 0 ) {
          newY = 0;
        }

        currentDragDiv.position(newX, newY);
    }
}