Question

I have seen a lot of frameworks and extensions recently and all for a lot of different things. It is hard for me to do things using just raw JavaScript or raw jQuery. I want to use these JS extensions/frameworks but the problem is that I don't know how to link them to my HTML document.

For Example: <script src="some link of fw/ext" type="text/javascript"></script> I put this in the <head> of my HTML and then write my code in a different file named "script.js" (made using notepad) but the code doesn't seem to work.

I know this is a problem because I don't link it properly.

I want to work with fabric.js on a project related to HTML5 canvas. I think I need to link both, my code and the framework in some way but I'm not sure as to how should I do it.

My HTML code :

<!DOCTYPE html>
<html>
<head>
<title>Code Example</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javscript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
</head>
<body>
 <canvas id="draw" width="250px" height="250px">This if browser doesn't support HTML5
 </canvas>
</body>
</html>

My JS Code:

var canvas = new fabric.Canvas('draw');
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 100;
canvas.freeDrawingBrush.color = "#ff0000";  

Should work somewhat like this : http://jsfiddle.net/MartinThoma/B525t/5/

Was it helpful?

Solution

You need to load fabric.js first at the header and then you need to load your js file order matters.

<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js'></script> 

<script type='text/javascript' src='yourjsfile.js'></script

In case you are not clear on how to add elements to the canvas. Then here is one snippet which could help you.

Also wrap your code inside onload() function so that when the script loads, the #draw element is available

window.onload = function() {

    var canvas = new fabric.Canvas('draw');
        canvas.isDrawingMode = true;
        canvas.freeDrawingBrush.width = 5;
        canvas.freeDrawingBrush.color = "#ff0000";

    // create a rectangle object
    var rect = new fabric.Rect({
      left: 100,
      top: 100,
      fill: 'red',
      width: 20,
      height: 20
    });
    // you need to add the object to canvas
    canvas.add(rect);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top