Skip to main content

Changing images at runtime

This tutorial will show you how to change the image used in FSI Viewer at runtime. This can be useful, for example, if you have an online shop where you have different image thumbnails next to FSI Viewer. When a customer clicks on one of the thumbnails to explore the product details, the image displayed in FSI Viewer will change. Instead of reloading the entire page, all you need to do is call the changeImage function of the FSI Viewer API.

Create FSI Viewer & Thumbnails

First we create an FSI Viewer instance with some clickable thumbnails.

You can find the complete HTML file in the GitHub tutorial resources.

<body onload="switchImageSample();">
<div>
<div style="float:left">
<fsi-viewer
id="myViewer"
width="400"
height="369"
src="sample_images/bags/80610_1.tif"></fsi-viewer>
</div>

<div id="img1">
<img
alt=""
src="//[server]/fsi/server?type=image&source=sample_images%2Fbags%2F80610_1.tif&height=123&format=jpeg"
width="123" />
</div>

<div id="img2">
<img
alt=""
src="//[server]/fsi/server?type=image&source=sample_images%2Fbags%2F80610_2.tif&height=123&format=jpeg"
width="123" />
</div>

<div id="img3">
<img
alt=""
src="//[server]/fsi/server?type=image&source=sample_images%2Fbags%2F80610_3.tif&height=123&format=jpeg"
width="123" />
</div>
</div>
</body>

This creates an FSI Viewer JS instance we can access by its id myViewer and 3 thumbnail images to click on.

JS Functions

The function switchImageSample assigns the onClick-events to each of the thumbnails.

You can find the complete JS file in the GitHub tutorial resources.

function switchImageSample() {
// add "click" handler to all 3 thumbnail images
for (var i = 1; i < 4; i++) {
var el = document.getElementById('img' + i);
$FSI.addEvent(el, 'click', onThumbnailClick);
}
}

The function onThumbnailClick retrieves the individual src attributes of each image, takes the actual image path of the attribute by using getParameterValueFromURL and refers this to the viewer in order to change the image:

function onThumbnailClick() {
var img = this.getElementsByTagName('img');

if (img && img[0]) {
// get the src attribute of the <img> tag
var strImageURL = img[0].getAttribute('src');

// get the "source" parameter value from the URL
var src = $FSI.utils.getParameterValueFromURL(strImageURL, 'source');

// change the image in FSI Viewer
var parameters = {imagePath: src};
var viewer = document.getElementById('myViewer');
viewer.changeImage(parameters);
}
}

addEventListener('DOMContentLoaded', (event) => {
switchImageSample();
});

Load Script

Please keep in mind to load the created function correctly in the HTML body:

<body onload="switchImageSample();">
[...]
</body>