I'm trying to create stroke around images I've added to canvas using Fabric JS. The stroke I've added to a PNG with transparent background looked like this:

Although I'm trying to create stroke "around" the image and stick the stroke to the edges of the image, Fabric JS just creates a "square" stroke.
How can I accomplish stroke "around" the image, any thoughts? I can't seem to find any documentation or demo to accomplish what I'm trying to do.
Thank you
You can do it in few steps.
// this._ctx = context of canvas
this._ctx.shadowColor = '#fff';
this._ctx.shadowBlur = 3;
this._ctx.shadowOffsetX = 0;
this._ctx.shadowOffsetY = 0;
this._ctx.drawImage(img, 30, 30, img.width, img.height);
// get contents of blurry bordered image
const imgData = this._ctx.getImageData(
0,
0,
this._ctx.canvas.width - 1,
this._ctx.canvas.height - 1
);
const opaqueAlpha = 255;
// turn all non-transparent pixels to full opacity
for (let i = imgData.data.length; i > 0; i -= 4) {
if (imgData.data[i + 3] > 0) {
imgData.data[i + 3] = opaqueAlpha;
}
}
// write transformed opaque pixels back to image
this._ctx.putImageData(imgData, 0, 0);
this._ctx.shadowColor = '#aaa';
this._ctx.shadowBlur = 3;
this._ctx.shadowOffsetX = 0;
this._ctx.shadowOffsetY = 0;
this._ctx.drawImage(this._canvas, 0, 0);
// you can export your image to data url
const url = this._canvas.toDataURL();
// and you can add image from data url to fabric
fabric.Image.fromURL(url, oImg => {
this._cf.add(oImg);
});
It will work, but for better user experience you should think, how you will do it dynamically (I'm working on it right now), I mean: user add an image, you want to give him option to "stroke" or not and blah-blah..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With