Search code examples
javascriptjointjs

Use JonintJS,How do I draw a graph on the canvas after the page is loaded?


I've been using on JointJS to draw flow chart on the page, very upset, currently only found JointJS can only be mapped the graphics before the page is loaded, and as a result, I want by click a button, a graphics (such as rectangle) paint on the canvas, simple code architecture is as follows:

<button onclick='addCell()'/>
<div id='paper'/>

var graph = new joint.dia.Graph();
var paper = new joint.dia.Paper({
            el: $('#paper'),
            width: 1580,
            height: 450,
            gridSize: 1,
            model: graph,
            perpendicularLinks: true
        });
var r1 = new joint.shapes.basic.Rect({
            position: {
                x: 10,
                y: 10
            },
            size: {
                width: 100,
                height: 40
            },
            attrs: {
                text: {
                    text: 'Rect1'
                }
            }
        });
function addCell(){
   graph.addCells(r1);
}

Give me an idea and thank you in advance for your response.


Solution

  • Your code is essentially correct but there is some HTML inaccurate syntax:

    <div id="paper"></div>
    <button id="btn-layout", onclick="addCell()">Add cell</button>
    
    <!-- code -->
    <script type="text/javascript">
    
    var graph = new joint.dia.Graph();
    var paper = new joint.dia.Paper({
                el: $('#paper'),
                width: 1580,
                height: 450,
                gridSize: 1,
                model: graph,
                perpendicularLinks: true
            });
    var r1 = new joint.shapes.basic.Rect({
                position: {
                    x: 10,
                    y: 10
                },
                size: {
                    width: 100,
                    height: 40
                },
                attrs: {
                    text: {
                        text: 'Rect1'
                    }
                }
            });
    function addCell(){
       graph.addCells(r1);
    }
    </script>
    

    Also don't forget to include the JointJS dependecies as described in the installation tutorial.