Fabric.js define bounds/limits for images

半世苍凉 提交于 2019-12-18 12:44:51

问题


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


来源:https://stackoverflow.com/questions/18744506/fabric-js-define-bounds-limits-for-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!