Drawing A Shape
by Roman Bruckner
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.2.0/joint.css" />
</head>
<body>
<!-- content -->
<div id="paper"></div>
<!-- dependencies -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.0/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.2.0/joint.js"></script>
</body>
</html>
JavaScript
var graph = new joint.dia.Graph({}, {
cellNamespace: joint.shapes
});
const paper = new joint.dia.Paper({
el: document.getElementById('paper'),
width: 800,
height: 900,
model: graph,
cellViewNamespace: joint.shapes
});
paper.on('blank:pointerdown', function(evt, x, y) {
const rect = new joint.shapes.standard.Rectangle({
position: {
x: x,
y: y
},
size: {
width: 1,
height: 1
}
});
rect.addTo(graph);
evt.data = {
rect,
ox: x,
oy: y
};
});
paper.on('blank:pointermove', function(evt, x, y) {
const {
ox,
oy,
rect
} = evt.data;
const bbox = new g.Rect(ox, oy, x - ox, y - oy);
if (bbox.width === 0) bbox.width = 1;
if (bbox.height === 0) bbox.height = 1;
bbox.normalize();
evt.data.bbox = bbox;
rect.set({
position: { x: bbox.x, y: bbox.y },
size: { width: bbox.width, height: bbox.height }
});
});
paper.on('blank:pointerup', function(evt, x, y) {
const {
ox,
oy,
rect,
bbox
} = evt.data;
if (bbox) return;
// do not leave tiny rectangles in the graph
rect.remove();
});