Back to Demos

This demo shows how you can convert a bitmap image to a shape.




var imageName = '';

function generateShape() {
  // First, clean up previous image/shape nodes
  var prevShapeNode = api.scene.find('svgShapeNode');
  if (prevShapeNode) {
    api.sceneGraph.deleteNode(prevShapeNode);
  }
  var prevImageNode = api.scene.find(imageName + '.svg');
  if (prevImageNode) {
    api.sceneGraph.deleteNode(prevImageNode);
  }

  // Then, process the new parameters
  var file = document.getElementById('fileUpload').files[0];
  var backgroundColor = document.getElementById('backgroundColor').value;
  imageName = file.name.split('.')[0];
  var threshold = document.getElementById('threshold').value;

  // Convert the uploaded image to an svg and create an image node from it
  api.assets
    .importImage(file, {
      targetFormat: 'svg',
      mode: 'threshold',
      threshold: threshold,
      backgroundColor: backgroundColor,
      outputName: imageName,
    })
    .then(function() {
      // Now that we have an svg image node, we can generate geometry from it using the SVGShape operator

      var shapeNodeName = 'svgShapeNode';

      api.scene.addNode({
        name: shapeNodeName,
        type: 'Shape',
        parent: api.scene.find('Objects'),
        plugs: {
          Shape: [
            [
              'SVGShape',
              {
                image: api.scene.find(imageName + '.svg'),
                curveSegments: 8,
              },
            ],
          ],
        },
      });

      // Resize shape (default operation is to fit a 1x1 square)
      api.scene.addOperator(
        api.scene.find(shapeNodeName),
        'Shape',
        'ResizeShape',
        { keepAspectRatio: true }
      );

      // Center the shape since center of svg is on top left corner
      api.scene.addOperator(
        api.scene.find(shapeNodeName),
        'Shape',
        'CenterShape',
        {}
      );
    });
}