Search code examples
htmlfabricjs

Background Gradient in Fabric.js


Using Fabric.js, is it possible to set the background to a gradient? For example something like:

http://www.html5canvastutorials.com/tutorials/html5-canvas-linear-gradients/


Solution

  • Well you could add a rectangle with a gradient as soon as the canvas is initialized. Set the height and width of the rectangle to the height and width of the canvas. starting from (x,y)->(0,0)

    var rect = new fabric.Rect({
      left: 0,
      top: 0,
      width: 1200,
      height: 1200
    });
    
    
    rect.setGradient('fill', {
      x1: 0,
      y1: rect.height,
      x2: rect.width,
      y2: rect.height,
      colorStops: {
        0: "red",
        1: "blue"
      }
    });