Search code examples
javascriptimagecanvasfabricjs

Apply frame image on top of Fabric JS Canvas


I am using Fabric JS to allow the user to have an interactive experience on my React app. Is it possible to apply a frame around a Fabric JS that is taken from an image? For instance, if the canvas is 400x400 px I can resize an image of a frame that is transparent in the middle to 410x410px and apply it on top of the canvas for the user to see? I have attached two images for reference.

Edit: This is the code I am using for zooming in

 const zoomIn = useCallback(() => {
    // Get original height of canvas
    const canvasDimensions = getInitialCanvasSize()

    let zoom = HTML5Canvas.getZoom()
    zoom += 0.2
    if (zoom >= 2) zoom = 2
    HTML5Canvas.setZoom(zoom)

    HTML5Canvas.setWidth(canvasDimensions.width * HTML5Canvas.getZoom());
    HTML5Canvas.setHeight(canvasDimensions.height * HTML5Canvas.getZoom());

  }, [HTML5Canvas])

Solution

  • There is no option for canvas's border in fabricjs canvas docs

    But you can still achieve this easily using following steps.

    PART 1: Creating the Illusion of border

    CSS Method

    1. First one can easily create CSS border around the canvas.
      Best way to do this is to create div around canvas, as fabricjs split canvas in 2 while running.
    2. You can create slider to control width and color/image for div's border.
      This will looks like exactly your second image with customization.

    OR

    Another Canvas Method

    Behind current canvas put this second canvas and control its width and image.
    I don't recommend this one, as this will make it more complex to implement.

    PART 2: Making Illusion real

    If you used CSS METHOD

    Now you get what your canvas looks like. You have width of border, image/color of border.

    Steps:

    1. Create new canvas (lets' call it 2nd Canvas) of 410px if canvas's width 400px with border of 5px.
    2. Export main canvas as image and put it over 2nd Canvas. And now you can export this as final image. For 2nd step check my answer on this stack

    If you used Another Canvas Method

    Directly follow above 2nd step

    Export main canvas as image and put it over 2nd Canvas. And now you can export this as final image. For 2nd step check my answer on this stack