'Is there any way to add a pattern to the stroke of moveable line
Here is my code to add the pattern to the stroke of the moveable line. when I try to move the line, the pattern remains in the same position. It should move inside the stroke according to the stroke's angle. Is there any way to adjust the stroke pattern? When the color is applied to the normal stroke it works fine. Kindly someone suggests how can I rectify this problem. And if there is any other method to make a zigzag line on canvas that can move to and fro, can be resized, and can be rotated according to the requirement just like a normal line.
image used for pattern is attached with the file
window.canvas = canvas;
let pic = 'http://127.0.0.1:5500/sin-small.png'
function loadPattern(url) {
fabric.util.loadImage(url, function(img) {
let pattern = new fabric.Pattern({
source: img,
repeat: 'repeat-x'
});
console.log(pattern)
line.set('stroke', pattern)
canvas.renderAll();
});
}
var canvas = new fabric.Canvas('c', {
selection: true
});
var line = new fabric.Line([50, 50, 100, 100], {
fill: 'red',
stroke: 'red',
strokeWidth: 10,
selectable: true,
hasControls: false,
hasBorders: false,
centeredRotation: false,
centeredScaling: false,
//originX: 'center',
//originY: 'center'
});
var circle1 = new fabric.Circle({
radius: 5,
fill: 'green',
left: 45,
top: 45,
hasControls: false,
hasBorders: false,
name: 'circle1'
});
var circle2 = new fabric.Circle({
radius: 5,
fill: 'green',
left: 95,
top: 95,
hasControls: false,
hasBorders: false,
name: 'circle2'
});
canvas.on('object:moving', function (options) {
var objType = options.target.get('type');
var p = options.target;
if (objType == 'line') {
var _l = line.left;
var _t = line.top;
circle1.set({
'left': (line.calcLinePoints().x1 + _l),
'top': (line.calcLinePoints().y1 + _t)
});
circle1.line.set({
'x1': circle1.left,
'y1': circle1.top
});
circle1.line.setCoords();
circle2.set({
'left': (line.calcLinePoints().x2 + _l),
'top': (line.calcLinePoints().y2 + _t)
});
circle2.line.set({
'x2': circle2.left,
'y2': circle2.top
});
circle2.line.setCoords();
canvas.renderAll();
}
if (objType == 'circle') {
if (p.name == 'circle1') {
line.set({
x1: circle1.getCenterPoint().x, y1: circle1.getCenterPoint().y, selectable: true
});
} else {
if (p.name == 'circle2') {
line.set({
x2: circle2.getCenterPoint().x, y2: circle2.getCenterPoint().y, selectable: true
});
}
}
}
line.setCoords();
circle1.setCoords();
circle2.setCoords();
canvas.renderAll();
});
canvas.add(line);
loadPattern(pic);
circle1.line=line;
circle2.line=line;
canvas.add(circle1);
canvas.add(circle2);
canvas.renderAll();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
