Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stroke for Custom Image in Fabric JS

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:

enter image description here

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

like image 768
platypus Avatar asked Mar 20 '26 08:03

platypus


1 Answers

You can do it in few steps.

  1. Upload png image to Canvas
  2. add "sticker stroke effect" (from this article)
      // 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);
  1. Export data to base64 and paste it through fabric
      // 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..

like image 179
Max P Avatar answered Mar 25 '26 17:03

Max P