Daniele Sassoli
Daniele Sassoli

Reputation: 898

How to use fabricjs

Hy I'm very new to canvas, I'm trying to learn how to use fabricjs but I can't get even the very basic example to work and it's quite frustrating. I downloaded the fabricjs-1.4.8.zip file and the only file I'm using is dist/fabric.min.js, here is my html code

<html>
  <head>
    <script type="text/javascript" src="jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="fabric.js-1.4.8/dist/fabric.js"></script>
    <script tye="text/javascript" src="test.js"></script>
  </head>
  <body>
    <canvas id="myCanvas" width="200" height="100"
     style="border:1px solid #000000;">
    </canvas>
  </body>
</html>

In first place I didn't include jquery, but after seeing many examples looked like that could do the trick, but it didn't for me, maybe I'm including a wrong version? and this is my test.js file

  var canvas = new fabric.Canvas('myCanvas');

  // create a rectangle with angle=45
  var rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: 'red',
    width: 20,
    height: 20,
    angle: 45
  });
  canvas.add(rect);

I can se the border of my canvas element, but no rectangle inside. Can someone see what I'm doing wrong? thanks

Upvotes: 0

Views: 1372

Answers (1)

IGNIS
IGNIS

Reputation: 440

It looks like your canvas is 200 x 100. But you're trying to draw a rectangle 100 pixels from the top. Your code probably works, but the rectangle doesn't show up because it's drawn at the bottom of the canvas. Try changing this line

top: 100

to this:

top: 0

UPDATE

If this doesn't work at first, it could be because the DOM hasn't loaded before your script runs. You can put your code in a jQuery document ready listener like so:

$(document).ready(function(){
   //Your code here...
});

This will ensure that the canvas element is actually ready to be used by the time your script fires. Best of luck!

Upvotes: 1

Related Questions