Fabric.js define bounds/limits for images

2019-02-05 09:55发布

问题:

I've set up a fabric.js based t-shirt simulator. Everything works as expected except for one detail that the client would like to get solved, being that disallowing an uploaded image to get past the t-shirt canvas (we could see it as the background image).

I've this background image in png and svg as well but how could I accomplish?

EDIT:

Based on the image, I'd like the image in the center of the tshirt to not be able to get dragged outside the red line... this would be the ideal scenario. If this is hard to do in a simple way, I'd be happy if I could bound the image to the blue line.

In this last case, I know I can clip the image to a form of a rectangle, but, is there any way that I can make the image stop when it hits the line, instead of just going under it?

Thanks

回答1:

According to kangax's advice:

canvas.on ("object:moving", function (event) {
        var el = event.target;

        // suppose el coords is center based

        el.left = el.left < el.getBoundingRectWidth() / 2 ? el.getBoundingRectWidth() / 2 : el.left;
        el.top = el.top < el.getBoundingRectHeight () / 2 ? el.getBoundingRectHeight() / 2 : el.top;

        var right = el.left + el.getBoundingRectWidth() / 2;
        var bottom = el.top + el.getBoundingRectHeight() / 2;

        el.left = right > canvas.width - el.getBoundingRectWidth() / 2 ? canvas.width - el.getBoundingRectWidth() / 2 : el.left;
        el.top = bottom > canvas.height - el.getBoundingRectHeight() / 2 ? canvas.height - el.getBoundingRectHeight() / 2 : el.top;
    });