Time-based SVG

Code

// Determine shape and color based on current milliseconds
const now = new Date();
const milliseconds = now.getMilliseconds();

// If milliseconds is even, draw a green circle. Else, a crimson rectangle.
const isEven = milliseconds % 2 === 0;
const color = isEven ? 'green' : 'crimson';
const shapeType = isEven ? 'circle' : 'rect';

console.log(`Milliseconds: ${milliseconds}. Drawing ${color} ${shapeType}.`);

try {
    // 1. Clear existing SVG content
    while (svgDom.firstChild) {
        svgDom.removeChild(svgDom.firstChild);
    }

    // 2. Create the new geometric shape
    const shape = document.createElementNS("http://www.w3.org/2000/svg", shapeType);

    if (shapeType === 'circle') {
        shape.setAttribute('cx', '50');
        shape.setAttribute('cy', '50');
        shape.setAttribute('r', '40');
    } else {
        shape.setAttribute('x', '10');
        shape.setAttribute('y', '10');
        shape.setAttribute('width', '80');
        shape.setAttribute('height', '80');
    }

    shape.setAttribute('fill', color);
    shape.setAttribute('stroke', 'black');
    shape.setAttribute('stroke-width', '2');

    // 3. Add text label
    const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    text.setAttribute('x', '50');
    text.setAttribute('y', '50');
    text.setAttribute('dominant-baseline', 'middle');
    text.setAttribute('text-anchor', 'middle');
    text.setAttribute('fill', 'white');
    text.setAttribute('font-family', 'Arial');
    text.setAttribute('font-size', '12');
    text.textContent = `ms: ${milliseconds}`;

    // 4. Append elements to SVG
    svgDom.appendChild(shape);
    svgDom.appendChild(text);

} catch (err) {
    console.error("Error in Open HMI script:", err);
    
    // Fallback display in SVG
    const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    text.setAttribute('x', '10');
    text.setAttribute('y', '20');
    text.setAttribute('fill', 'red');
    text.textContent = "Error executing script";
    svgDom.appendChild(text);
}

// Return the modified DOM
return svgDom;