使用JonintJS,如何在页面加载后在canvas上绘制图形?

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

一直在用JointJS在页面上画流程图,很苦恼,目前只发现JointJS只能在页面加载前映射图形,结果我想点击一个按钮,在canvas上绘制一个图形(比如矩形),简单的代码架构如下:

<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);
}

给我一个想法,提前感谢您的回复。

您的代码基本上是正确的,但有一些 HTML 不准确 语法:

<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>

另外不要忘记包含 installation tutorial 中描述的 JointJS 依赖项。