Demos

Replace placeholder with user upload

Bind placeholder images to a template variable and replace them with user-selected photos that crop to the frame

Use this approach when you want to give users the ability to quickly replace a default placeholder image in their design with a custom photo. This is useful for flyers, posters, and other templates where large images can be swapped out.

1. Mark an Image as a Placeholder

Bind the image's src to a template variable and give it a fit, so any photo that replaces it crops to the frame:

const width = 600;
const height = 400;
// Add a placeholder image element
// you can make you own with your own text
// placehold.co is just an example, better to use your own image
store.activePage.addElement(
  {
    type: 'image',
    src: 'https://placehold.co/600x400?text=Click+to+add+image',
    x: (store.width - width) / 2,
    y: (store.height - height) / 2,
    width,
    height,
    // the bound src marks the placeholder
    bindings: { src: 'photo' },
    // a new photo of any shape fills the frame
    fit: 'cover',
  },
  { skipSelect: true }
);

2. Detect When the Placeholder Is Selected

Watch for changes in store.selectedElements. If a placeholder image is selected, show an “Upload Your Picture” button or open a file picker immediately.

3. Replace the Placeholder Image

Once a user selects an image file, set the element’s src to the URL of that file. Setting a bound property by hand detaches its binding, so the image stops being a placeholder, and undo restores it. fit: 'cover' stays, so the photo fills the frame whatever its shape.

Implementation Example

Below is a minimal React-based implementation. The key points are:

  • A hidden file input used to pick images
  • A MobX reaction or state check to detect when the user selects the placeholder
  • Replacing the placeholder image with the uploaded file
import React from 'react';
import { reaction } from 'mobx';

export function usePlaceholderSelection(store: any) {
  const fileInputRef = React.useRef<HTMLInputElement | null>(null);

  // react to selected elements
  React.useEffect(() => {
    // Dispose reaction when component unmounts
    const dispose = reaction(
      () => store.selectedElements,
      (selectedElements: any[]) => {
        // Check if at least one selected element is a placeholder
        const placeholder = selectedElements.find(
          (el) => el.type === 'image' && el.bindings?.src
        );
        if (placeholder) {
          // Trigger the hidden file input
          fileInputRef.current?.click();
        }
      }
    );
    return () => dispose();
  }, [store]);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async (loadEvent) => {
      // we will use dataURL to set the image
      // but it is recommended to upload image to the server first
      // for better performance and smaller JSON export
      const dataURL = loadEvent.target?.result as string;
      // Find the currently selected placeholder element
      const placeholder = store.selectedElements.find(
        (el: any) => el.type === 'image' && el.bindings?.src
      );
      if (!placeholder) return;

      // detaches the binding; fit: 'cover' crops the photo to the frame
      placeholder.set({ src: dataURL });
    };
    reader.readAsDataURL(file);
    // Reset the file input so selecting the same file triggers onChange again
    e.target.value = '';
  };

  // Return a hidden file input to be triggered by the reaction
  return (
    <input
      ref={fileInputRef}
      type="file"
      style={{ display: 'none' }}
      accept="image/*"
      onChange={handleFileChange}
    />
  );
}

3. Use the Hook in Your App

import React from 'react';
import { PolotnoContainer, SidePanelWrap, WorkspaceWrap } from 'polotno';
import { Toolbar } from 'polotno/toolbar/toolbar';
import { PagesTimeline } from 'polotno/pages-timeline';
import { ZoomButtons } from 'polotno/toolbar/zoom-buttons';
import { SidePanel } from 'polotno/side-panel';
import { Workspace } from 'polotno/canvas/workspace';

export const App = ({ store }: { store: any }) => {
  const fileInput = usePlaceholderSelection(store);

  return (
    <PolotnoContainer style={{ width: '100vw', height: '100vh' }}>
      <SidePanelWrap>
        <SidePanel store={store} />
      </SidePanelWrap>
      <WorkspaceWrap>
        <Toolbar store={store} downloadButtonEnabled />
        <Workspace store={store} />
        {fileInput}
        <ZoomButtons store={store} />
        <PagesTimeline store={store} />
      </WorkspaceWrap>
    </PolotnoContainer>
  );
};

Optional: Control How New Images Fit

  • fit: 'cover' fills the frame and crops the overflow.
  • fit: 'contain' shows the whole photo inside the frame.
  • focus: { x, y } aligns the source in the frame, like CSS object-position: 0 holds its left or top edge, 1 its right or bottom edge, and 0.5, the default, centers it. With cover it picks the part that stays in view; with contain it places the source in the spare space.
// keep faces in view: hold the crop nearer the top of a portrait
placeholder.set({ fit: 'cover', focus: { x: 0.5, y: 0.3 } });

Every renderer computes the crop from fit when it draws, so the photo crops the same on the canvas and in each export. Setting a crop (cropX, cropWidth, …) removes fit. See Keep a good crop with fit and focus.

Keep the Template

To keep the image bound, write the photo into the design's variables instead of the element. Every element bound to photo then shows it, and the design stays a template:

const photo = store.variables?.find((v) => v.name === 'photo');
const others = (store.variables ?? []).filter((v) => v !== photo);
store.setVariables([...others, { ...photo, name: 'photo', value: dataURL }]);

Alternative UI Approaches

  • Manual Button: Display a button in the Toolbar or Tooltip that opens the file dialog.
  • Side Panel Section: Create a custom side panel tab that appears only when a placeholder is selected.

Tips

  • Bind src to a variable to mark a replaceable image. getVariables lists it as an image field.
  • Set fit on the placeholder, so a photo of any shape crops to the frame without crop math.
  • For best results, upload images to a server first instead of using data URLs.

Live demo

On this page