我正在使用动态模式来填充 SVG 图像。它可以很好地呈现模式,但我无法像FabricJs 教程中提到的那样在运行时转换模式。
以下是我的代码:
<div>
<p>
<label>Repeat pattern?</label>
<input type="checkbox" id="img-repeat" checked>
</p>
<p>
<label>Pattern image width</label>
<input type="range" min="50" max="1000" value="100" id="img-width">
</p>
<p>
<label>Pattern left offset</label>
<input type="range" min="0" max="500" value="0" id="img-offset-x">
</p>
<p>
<label>Pattern top offset</label>
<input type="range" min="0" max="500" value="0" id="img-offset-y">
</p>
<br>
<p>
<label>Pattern image angle</label>
<input type="range" min="-90" max="90" value="0" id="img-angle">
</p>
<p>
<label>Pattern image padding</label>
<input type="range" min="-50" max="50" value="0" id="img-padding">
</p>
</div>
<canvas id="c" width="500" height="500" style="border:1px solid #ccc"></canvas>
以下是我的 Js 代码。
(function () {
var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
var padding = 0;
fabric.loadSVGFromURL('images/bottom.svg', function (objects, options) {
var oSvg = fabric.util.groupSVGElements(objects, options);
fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function (img) {
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.setDimensions({
width: img.getScaledWidth(),
height: img.getScaledHeight()
});
patternSourceCanvas.add(img);
var pattern = new fabric.Pattern({
source: patternSourceCanvas.getElement(),
repeat: 'repeat'
});
oSvg.getObjects().forEach(function (e) {
e.fill = pattern
});
canvas.add(oSvg);
document.getElementById('img-width').oninput = function () {
img.scaleToWidth(parseInt(this.value, 10));
console.log('img-width');
canvas.requestRenderAll();
};
document.getElementById('img-angle').oninput = function () {
img.set('angle', this.value);
console.log('img-angle');
canvas.requestRenderAll();
};
document.getElementById('img-padding').oninput = function () {
padding = parseInt(this.value, 10);
console.log('img-padding');
canvas.requestRenderAll();
};
document.getElementById('img-offset-x').oninput = function () {
pattern.offsetX = parseInt(this.value, 10);
canvas.requestRenderAll();
};
document.getElementById('img-offset-y').oninput = function () {
pattern.offsetY = parseInt(this.value, 10);
console.log('img-offset-y');
canvas.requestRenderAll();
};
document.getElementById('img-repeat').onclick = function () {
pattern.repeat = this.checked ? 'repeat' : 'no-repeat';
console.log('img-repeat');
canvas.requestRenderAll();
};
});
});
})();
每当我更改任何上述范围滑块时,它就会生效。让我知道我做错了什么。