A little more ViewSTL

Basic usage.

One container, one model and a few lines of JavaScript.

Working example · ViewSTL 2.0.0-rc.6

Opening example…

View code

Copy the complete build/ folder from the plugin download beside this HTML file, add the models below, and serve the folder over HTTP(S). This is the same example program with local file paths.

These are the original legacy ViewSTL example models. Save the required files in a models/ folder beside your HTML: viewstl_plugin.stl.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ViewSTL — Basic usage</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 20px; }
    #example-viewer { width: 100%; height: 500px; }
    button { padding: 10px 16px; }

  </style>
</head>
<body>
  <div id="example-viewer"></div>
  <p id="example-status" role="status">Opening example…</p>
  <button id="example-retry" type="button" hidden>Retry example</button>

  <script type="module">
import StlViewer from './build/viewstl.js';

const container = document.getElementById('example-viewer');
const status = document.getElementById('example-status');
const retry = document.getElementById('example-retry');
const modelURL = new URL('./models/viewstl_plugin.stl', import.meta.url).href;

let loadError = null;
function showError(message) {
  loadError = message;
  status.textContent = message;
  retry.hidden = false;
}
retry.addEventListener('click', () => location.reload());

const viewer = new StlViewer(container, {
  models: [{ id: 0, filename: modelURL, color: '#64a5b2' }],
  load_error_callback: showError
});

// Refit through the plugin when the example container changes width.
let lastWidth = container.clientWidth;
const resize = new ResizeObserver(() => {
  if (container.clientWidth === lastWidth) return;
  lastWidth = container.clientWidth;
  viewer.do_resize();
  viewer.set_auto_zoom();
});
resize.observe(container);

try {
  await viewer.when_idle();
  if (loadError) throw new Error(loadError);
  viewer.set_camera_view('isometric');
  status.textContent = 'Ready. Drag to rotate, scroll to zoom. Keyboard: arrows, + / − and F.';
} catch (error) {
  showError(error.message);
  viewer.dispose();
}
addEventListener('pagehide', event => { if (!event.persisted) { resize.disconnect(); viewer.dispose(); } });
  </script>
</body>
</html>

These are the original legacy ViewSTL example models. Save the required files in a models/ folder beside your HTML: viewstl_plugin.stl.

← Relevant documentation