To add a mouse tracking spotlight to your project, create an Embed & Code widget. Double-click on it and insert the following code into its Before </BODY> section (removing all the rest):
<script>
let renderContainer, canvas, context;
const updateContextSize = () => {
if (canvas) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
};
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
if (RM.viewerRouter && RM.viewerRouter.mag.getMagViewport() === 'default') {
renderTorch();
} else if (RM.constructorRouter) {
RM.constructorRouter.on('previewMag:load:success', (preview) => {
if (preview.mag.getMagViewport() === 'default') {
renderTorch();
}
});
}
window.addEventListener('resize', updateContextSize);
}, 1000);
});
const renderTorch = () => {
// parameters
const radius = 150;
const backgroundColor = 'rgba(0,0,0,0.8)';
let x = -200, y = -200;
// init
renderContainer = document.createElement('div');
renderContainer.setAttribute('id', 'render-container');
renderContainer.setAttribute("style", "pointer-events: none; position: fixed; z-index: 100; top: 0; left: 0; width: 100%; height: 100%; background-color: transparent;");
document.body.appendChild(renderContainer);
canvas = document.createElement('canvas');
canvas.setAttribute('id', 'render-canvas');
renderContainer.appendChild(canvas);
context = canvas.getContext('2d');
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight;
// Fill bg
context.fillStyle = backgroundColor;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
// Mouse event
document.addEventListener('mousemove', (event) => {
x = event.clientX;
y = event.clientY;
});
const draw = () => {
requestAnimationFrame(draw);
// first reset the gCO
context.globalCompositeOperation = 'source-over';
// Fill bg
context.fillStyle = backgroundColor;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.beginPath();
radialGradient = context.createRadialGradient(x, y, 1, x, y, radius);
radialGradient.addColorStop(0, 'rgba(255,255,255,1)');
radialGradient.addColorStop(1, 'rgba(0,0,0,0)');
context.globalCompositeOperation = 'destination-out';
context.fillStyle = radialGradient;
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.fill();
context.closePath();
};
requestAnimationFrame(draw);
};
</script>
This spotlight is fully customizable: try changing radius, color, or opacity (// parameters section in the code) to give it a unique look. For example, try changing the code parameters to:
const radius = 500;
const backgroundColor = ‘rgba(255,0,100,1)’;
The result: