简体   繁体   中英

Keep KineticJS shapes inside canvas

Is there a simple way to make sure that your shapes stay inside the canvas, when using the drag&drop functionality from KineticJS?

Standard, the shape leaves the canvas a bit until your mouse hits the canvas border. I would like that to be the shapes border, instead of the mouse.

Is there a way to make that happen?

Use dragBoundFunc explained in the KineticJS tutorial

Here's a JS fiddle

And the code:

dragBoundFunc: function(pos) {
    console.log(bbox.getWidth());
    var xBound = stage.getWidth() - bbox.getWidth();
    var yBound = stage.getHeight() - bbox.getHeight();

    // Check X boundries
    if (pos.x > xBound) {
        var newX = xBound;
    } else if (pos.x <= 0) {
        var newX = 0;
    } else {
        var newX = pos.x;
    }

    // Check Y boundries
    if (pos.y > yBound) {
        var newY = yBound;
    } else if (pos.y <= 0) {
        var newY = 0;
    } else {
        var newY = pos.y;
    }

    return {
        x: newX,
        y: newY
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM