How to include adornments in exported image?

I just noticed adornments won’t appear in the exported image. In the following image, the top left box is the result of export and the middle one is the actual diagram:

Here’s the code I’m using:

const d = go.GraphObject.make(go.Diagram, 'box');

function exportImage(d: go.Diagram) {
  const img = document.createElement('img');
  const imgStyle = {
    position: 'fixed',
    width: 'auto',
    height: 'auto',
    top: 0,
    backgroundColor: '#f7f7f7',
    border: '1px solid black',
    zIndex: 2147483647,
    padding: '16px',
  };

  const data =
    d.makeImageData({ scale: 1, type: 'image/png' })?.toString() ?? '';
  img.src = data;
  img.id = 'output';
  Object.assign(img.style, imgStyle);
  document.body.appendChild(img);
}

const exportBtn = document.querySelector('#export_btn');
exportBtn?.addEventListener('click', () => {
  exportImage(d);
});

function createAd(label: string) {
  const ad = new go.Adornment('Spot', {
    name: 'label_adornment',
    alignment: go.Spot.TopLeft,
    alignmentFocus: go.Spot.BottomLeft,
    isActionable: false,
  })
    .add(new go.Placeholder({ isActionable: false }))
    .add(
      new go.Shape('Circle', {
        fill: label,
        width: 12,
        height: 12,
      })
    );

  return ad;
}

const nodeTemplate = new go.Node(go.Panel.Spot, {
  isShadowed: true,
  shadowVisible: true,
  shadowOffset: new go.Point(0, 2),
  shadowColor: 'rgba(0, 0, 0, 0.4)',
  shadowBlur: 1,
})
  .add(
    new go.Shape('RoundedRectangle', {
      desiredSize: new go.Size(28, 28),
      fill: 'gold',
    })
  )
  .add(new go.TextBlock('').bind(new go.Binding('text', 'name')))
  .bind(
    new go.Binding('', 'label', (label: string, obj: go.GraphObject) => {
      const ad = createAd(label);
      ad.adornedObject = obj?.part;
      obj?.part?.addAdornment('blah', ad);
    })
  );

const linkTemplate = new go.Link()
  .add(new go.Shape({ strokeWidth: 2, stroke: 'black' }))
  .add(new go.Shape({ toArrow: 'Standard', alignment: go.Spot.Center }))
  .bind(new go.Binding('points').makeTwoWay());

d.nodeTemplate = nodeTemplate;
d.linkTemplate = linkTemplate;

const nodes = [
  { key: 'A', name: 'A', loc: '0 0', label: 'whitesmoke' },
  { key: 'B', name: 'B', loc: '200 200', label: 'green' },
  { key: 'C', name: 'C', loc: '600 250', label: 'pink' },
];

const links = [
  { from: 'A', to: 'B' },
  { from: 'B', to: 'C' },
];

d.model = new go.GraphLinksModel(nodes, links);

Is there any way I can include the adornments in the export?

In your call to Diagram.makeImageData set the showTemporary option to true. DiagramRendererOptions | GoJS API

By the way, we recommend using Diagram.makeSvg instead of rendering a raster image, so that you don’t have to worry about large bitmaps or resolution.

1 Like