Search code examples
javascripthtmlcanvashtml5-canvasfabricjs

How to add image on canvas with fabric


This is my first time using fabric.js. I want to add a picture on canvas but it doesn't work

this is my html

<canvas id="workCanvas" style="position: absolute; z-index:0; top:10%; left:10%"></canvas>

and this is js

function imageOnCanvas() {
    var canvas = new fabric.Canvas('#workCanvas')

    fabric.Image.fromURL("image/flower.jfif",function(myImg) {
        console.log(myImg);
        canvas.add(myImg);
    })
}

Solution

  • You should pass a id directly in the new fabric.Canvas("workCanvas");

    Ref. http://fabricjs.com/fabric-intro-part-1#why_fabric

    function imageOnCanvas() {
      var canvas = new fabric.Canvas("workCanvas");
    
      fabric.Image.fromURL(
        "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Example_image.svg/600px-Example_image.svg.png",
        function (myImg, err) {
          canvas.add(myImg);
          console.log(err);
        }
      );
    }
    
    imageOnCanvas();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
    
    <canvas id="workCanvas" style="position: absolute; z-index:0; top:10%; left:10%"></canvas>