如何使用P5js在不离开画布的情况下将DOM元素拖动到画布中?

时间:2018-10-13 21:25:58

标签: javascript canvas processing p5.js

我想要什么:

我有一个div,我想在画布上移动它,但将其限制为画布的宽度和高度

我所拥有的:

我正在使用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;
}

问题:

此代码运行良好,但是如果用户过快地移动鼠标,则直到出现this之类的画布边框之前,div都不会消失(我将div非常快地拖动并向右移动并停止在屏幕中间)。这个问题使变量onsetX和onsetY出错,并且使div偏离画布边界的距离变乱了。

是否可以删除此“错误”并使div移至画布的边框?

观察:

  1. 我删除了一些我认为对此问题没有必要的代码。
  2. 变量onsetX和onsetY与offsetX和offsetY相反,它是鼠标位置边框的位置,但是因为英语不是我的母语,所以我不知道如何命名该变量。建议会很好。

1 个答案:

答案 0 :(得分:1)

在当前代码中,如果超出了画布的边框,则完全省略了拖动:

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的范围内。这意味着您必须将拖动“限制”到此范围:

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