Fabric js自定义旋转图标未在初始加载时显示

时间:2016-09-12 14:02:05

标签: javascript html5-canvas fabricjs

我有以下代码用于更改fabric js中的旋转图标: http://jsfiddle.net/2XZHp/194/

//Replace rotate icon
isVML = function() { return typeof G_vmlCanvasManager !== 'undefined'; };

// overriding _drawControl method
fabric.util.object.extend(fabric.Object.prototype, {
    hasRotatingPoint: true,
    selectedIconImage: new Image(),
    iconSrc: 'http://www.navifun.net/files/pins/tiny/Arrow-Rotate-Clockwise.png',
    isLoaded: false,
    _drawControl: function(control, ctx, methodName, left, top) {
        if (!this.isControlVisible(control)) {
            return;
        }
        var size = this.cornerSize;
        isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
        if(control !== 'mtr')   ctx['fillRect'](left, top, size, size);
           if(control === 'mtr') {
            if (this.isLoaded) {
                ctx.drawImage(this.selectedIconImage, left, top, size, size);
            } else {
                var self = this;
                this.selectedIconImage.onload = function() {
                    self.isLoaded = true;
                    ctx.drawImage(self.selectedIconImage, left, top, size, size);
                }
                this.selectedIconImage.src = this.iconSrc;
            } 
        }
    }
});

但是第一次选择时没有显示旋转图标。只有当我开始移动对象时,或者取消选择它并再次选择它。

我已经看过其他改变图标的​​解决方案,但这个似乎是迄今为止最优雅的。但也许它太简单/有限?

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我不确定这是否符合您的需求,但添加一个简单的self.canvas.renderAll()可以解决问题:

http://jsfiddle.net/2XZHp/195/

if (control === "mtr") {
    if (self.isLoaded) {
        ctx.drawImage(self.selectedIconImage, left, top, size, size);
        console.warn("reusing");
    }
    else {
        self.selectedIconImage.onload = function() {
            self.isLoaded = true;
            ctx.drawImage(this, left, top, size, size);
            self.canvas.renderAll();
            console.warn("initial load");
        }
        self.selectedIconImage.src = self.iconSrc;
    } 
}
else {
    ctx.fillRect(left, top, size, size);
}

它也适用于self.render(ctx)

http://jsfiddle.net/2XZHp/196/