Imagine I have Rect element and I wish to decorate it with a small (say 16x16) PNG image in the upper left. I am unable to determine how to achieve that task. I have studied the docs but have (so far) been unable to find a sample or reference on how to achieve that task. Does anyone have a recipe or a sample pointer that they would be willing to share to help me achieve my goal?
How to add an image to an element as a decorator?
6.7k Views Asked by Kolban At
2
There are 2 best solutions below
0

We can create an element type for an image using the following recipe:
var image = new joint.shapes.basic.Image({
position : {
x : 100,
y : 100
},
size : {
width : 16,
height : 16
},
attrs : {
image : {
"xlink:href" : "images/myImage.png",
width : 16,
height : 16
}
}
});
graph.addCell(image);
This will position the image at x=100,y=100. It is important to make the size width/height match the attrs/image width/height and be the width/height of the image itself.
Although this doesn't decorate a previous element, it can be positioned over a previous element achieving the desired effect.
Better is to create your own custom shape that has a rectangle, image and text. This gives you much more flexibility and you don't have to have two elements in order to express one shape. Your shape decorated with a little image in the top left corner may look like:
And you can use it like this in your diagrams:
Note how is the shape specified, the important bits are the
markup
,type
and theattrs
object that references the SVG elements in the markup by normal CSS selectors (here just tag selectors but you can use classes if you want). For the image tag, we take advantage of the JointJS special attributes for relative positioning (ref
,ref-x
andref-y
). With these attributes, we position the image relatively to the top left corner of therect
element and we offset it by 2px from the top edge (ref-y
) and 2px from the left edge (ref-x
).One note: It is important that the
type
attribute ('basic.DecoratedRect') matches the namespace the shape is defined in (joint.shapes.basic.DecoratedRect
). This is because when JointJS re-constructs graphs from JSON, it looks at thetype
attribute and makes a simple lookup to thejoint.shapes
namespace to see if there is a shape defined for this type.