Fabric JS - 不显示形状

时间:2017-07-09 13:53:50

标签: javascript fabricjs

我正在使用FabricJS并且形状没有显示,我的代码在JSFiddle:

https://jsfiddle.net/270t9hfs/1/

var canvas = new fabric.Canvas("canvas");
    function addRectangle(){
                    var rect = new fabric.Rect({
                        left: 100,
                        top: 100,
                        fill: "red",
                        width: 20,
                        height: 20,
                        angle: 0
                    });
                    canvas.add(rect);
            }

1 个答案:

答案 0 :(得分:0)

以下示例具有有效的addRectangle功能:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>

    <style type="text/css">
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            width: 200px;
            background-color: #f1f1f1;
        }
        
        li a{
            display: block;
            color: #000;
            padding: 8px 16px;
            text-decoration: none;
        }
        
        /* Change the link color on hover */
        li a:hover {
            background-color: #555;
            color: white;
        }
        
        #canvas {
            border: 1px solid;
        }
        button { margin-top: 9px }
</style>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <button onclick="addRectangle()">Add Rectangle</button>
    <button onclick="addTriangle()">Add Triangle</button>
    <button onclick="addCircle()">Add Circle</button>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
    <script type="text/javascript">
    var canvas = new fabric.Canvas("canvas");
    function addRectangle(){
        var rect = new fabric.Rect({
            left: 100,
            top: 100,
            fill: "red",
            width: 20,
            height: 20,
            angle: 0
        });
        canvas.add(rect);
    }
    </script>
</body>
</html>

有两个问题破坏了你的代码:

  1. 缺少Fabric JS库
  2. 在加载DOM之前初始化Fabric JS画布。将JavaScript移动到页面底部可解决此问题。或者,您可以使用JavaScript来监听DOM加载的时间。