我有一个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移至画布的边框?
答案 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);
}
}