fabricjs clipTo is not working

青春壹個敷衍的年華 提交于 2019-12-14 02:23:03

问题


I have a simple script like:

fabric.Image.fromURL(url, function(oImg) { 
        oImg.set({selectable:false})
        oImg.clipTo = function(ctx) {
            console.log("ctx")
            console.log(ctx)
        }
    })

Here clipTo function is not called. I want to clip oImg but clipTo is not called.

What is wrong in here ?


回答1:


Gamer,

Here is working code:

var canvas = new fabric.Canvas('c1');
var src = "http://fabricjs.com/lib/pug.jpg";
canvas.backgroundColor = "#333";

var object;
fabric.util.loadImage(src, function (img) {
    object = new fabric.Image(img);
    object.set({
        left: 100,
        top: 100,
        selectable: false,
        clipTo: function(ctx) {
            console.log("ctx")
            console.log(ctx);
            ctx.rect(
                        2,
                        2,
                        430,
                        430
                    );
        }
    });
    object.hasRotatingPoint = true;
    object.scaleX = object.scaleY = 0.25;
    canvas.add(object);
    canvas.renderAll();
});

Actually, your code working fine as well. I believe only difference only with library version. I used 1.7.1 My guess it didn't work for you, because your image wasn't active or not loaded yet into canvas, and you tried to clip it.

Also, i used fabric.util.loadImage instead of fabric.Image.fromURL

For fabric.Image.fromURL you should make an active object and then set properties. To make an active object you should do something like this:

var objImg = null;
var image = fabric.Image.fromURL(img, function(oImg) {
                    oImg.set({width: oImg.width,
                              height: oImg.height,
                              left: 100,
                              top: 100,
                              originX: 'center',
                              originY: 'center',
                              selectable: false,
                              perPixelTargetFind: true,
                              transparentCorners: false});

                    canvas.setActiveObject(oImg);
                    objImg  = canvas.getActiveObject();
                    objImg.clipTo = function(ctx) {
                console.log("ctx")
                console.log(ctx);
                ctx.rect(
                            2,
                            2,
                            430,
                            430
                        );
            }
                    canvas.add(oImg);
});


来源:https://stackoverflow.com/questions/39787776/fabricjs-clipto-is-not-working

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