2016-09-17 384 views

回答

6

下面是一个简单的例子,其中在对象的比例尺上我们保留对原始笔画的引用并基于该尺度计算新的笔画。

var canvas = new fabric.Canvas('c', { selection: false, preserveObjectStacking:true }); 
 
window.canvas = canvas; 
 
canvas.add(new fabric.Rect({ 
 
    left: 100, 
 
    top: 100, 
 
    width: 50, 
 
    height: 50, 
 
    fill: '#faa', 
 
    originX: 'left', 
 
    originY: 'top', 
 
    stroke: "#000", 
 
    strokeWidth: 1, 
 
    centeredRotation: true 
 
})); 
 

 
canvas.on('object:scaling', (e) => { 
 
\t var o = e.target; 
 
\t if (!o.strokeWidthUnscaled && o.strokeWidth) { 
 
    \t o.strokeWidthUnscaled = o.strokeWidth; 
 
    } 
 
\t if (o.strokeWidthUnscaled) { 
 
    \t o.strokeWidth = o.strokeWidthUnscaled/o.scaleX; 
 
    } 
 
})
canvas { 
 
    border: 1px solid #ccc; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script> 
 
<canvas id="c" width="600" height="600"></canvas>

+0

您是否尝试导入svg。我知道它适用于这些内置形状,但不能导入svg。 – trongd

+0

我不知道任何任何svg好方法。让你的形状成为一条单一的道路。创建一个fabric.Path(),然后将笔画添加到该路径对象。 – StefanHayden

+1

对不起,这是我的错误。你的解决方案应该可行 – trongd

1

我发现什么感觉就像一个更好的解决方案,确实很好用SVG路径。

您可以覆盖fabricjs'_renderStroke方法并在ctx.stroke();之前添加ctx.scale(1/this.scaleX, 1/this.scaleY);,如下所示。

fabric.Object.prototype._renderStroke = function(ctx) { 
    if (!this.stroke || this.strokeWidth === 0) { 
     return; 
    } 
    if (this.shadow && !this.shadow.affectStroke) { 
     this._removeShadow(ctx); 
    } 
    ctx.save(); 
    ctx.scale(1/this.scaleX, 1/this.scaleY); 
    this._setLineDash(ctx, this.strokeDashArray, this._renderDashedStroke); 
    this._applyPatternGradientTransform(ctx, this.stroke); 
    ctx.stroke(); 
    ctx.restore(); 
}; 

您可能还需要重写fabric.Object.prototype._getTransformedDimensions调整的边框,以占规模上的差异。

此外,更完整的实现可能会添加一个结构对象属性,以有条件地控制这两个重写方法的更改。

相关问题