Reputation: 53
I'm using in my project fabricJS and I have problem to change stroke color and width. I have some SVG files on my page and after clicking user can add this SVG to canvas and modify its properties. With fill it works perfectly but with stroke I can't do the same. This is code for fill and it is working good:
function setImageColor(element)
{
var activeObject = canvas.getActiveObject(),
color = "#"+element.value;
console.log(color)
console.log(activeObject)
activeObject.set({fill : color});
canvas.renderAll();
}
jscolor.addEventListener('change', function()
{
setImageColor(this);
});
Here is code for loading SVG elements on canvas:
shapes.forEach(function(e)
{
e.addEventListener("click", function()
{
var src = e.src;
fabric.loadSVGFromURL( src, function(objects, options)
{
var obj = fabric.util.groupSVGElements(objects, options);
canvas.add(obj).renderAll();
obj.scaleToHeight(127)
.scaleToWidth(90)
.center()
.setCoords();
canvas.setActiveObject(obj).renderAll();
});
});
});
and here is code for the stroke and it is not working:
function setStrokeColor(element)
{
color = "#"+element.value;
var obj = canvas.getActiveObject();
console.log(color)
console.log(activeObject)
activeObject.set({stroke : color, strokeWidth: 5});
canvas.renderAll();
}
var stroke = document.getElementById("stroke");
console.log(stroke)
stroke.addEventListener('change', function()
{
setStrokeColor(this);
});
Upvotes: 5
Views: 5426
Reputation: 2407
This should do it (thanks for the SVG Path export):
Here's the FabricJS code:
fabric.loadSVGFromString('<svg id="Warstwa_1" data-name="Warstwa 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><defs><style>.cls-1{fill:none;stroke:#000;stroke-miterlimit:10;}</style></defs><title>generator ikon</title><path class="cls-1" d="M60,35A25,25,0,1,1,35,10,25,25,0,0,1,60,35Z"/></svg>', function(objects, options) {
var shape = fabric.util.groupSVGElements(objects, options);
shape.set({
left: 50,
top: 50,
scaleX: 3,
scaleY: 3
});
if (shape.paths) {
for (var i = 0; i < shape.paths.length; i++) {
shape.paths[i].set({
fill: 'red',
stroke: 'green',
strokeWidth: 5
});
}
}
object = shape;
canvas.add(shape);
canvas.renderAll();
});
var switchColors = true;
document.getElementsByTagName("button")[0].addEventListener('click', function() {
if (object.paths) {
for (var i = 0; i < object.paths.length; i++) {
object.paths[i].set({
fill: (switchColors ? 'green' : 'red'),
stroke: (switchColors ? 'red' : 'green'),
strokeWidth: (switchColors ? 10 : 5)
});
}
}
switchColors = !switchColors;
canvas.renderAll();
});
Here's the all important JSFiddle, https://jsfiddle.net/rekrah/wg2qxc8e/.
Let me know if you have anymore questions. I hope it helps!
Upvotes: 1