Ray by Day JS

Day 2 - Static SVG embedded in HTML

Day 2: Inline SVG and DOM Manipulation

Building on Day 1's external file approach, Day 2 demonstrates embedding SVG content directly within the HTML. This approach provides a small but important advantage over Day 1's use of a static SVG file: the ability to manipulate SVG elements as part of the Document Object Model (DOM).

When SVG is embedded inline (rather than loaded as an external file), each SVG element becomes a manipulable DOM node. This means we can use JavaScript to dynamically change colors, positions, sizes, and other properties of individual "pixels" in real-time, without needing to regenerate the entire image.

The image below shows a 10 × 10 pixel grid but, unlike on Day 1, it is now embedded directly in the HTML. This inline approach enables interactive features like the color manipulation controls you'll see below.

(Notice that the XML header is not used when the SVG content is included directly in the HTML.)

SVG Content embedded directly in HTML

STATIC IMAGE (sort of)

Try clicking the "Change Random Square" button to see how the SVG image content can now be dynamically change on this page, whereas the image shown on Day 1 was entirely static.

Try choosing a color below (using the HTML color code syntax) and row and column coordinates and then clicking on "Set Color at Position" to change the color of a specific pixel. Again, this is dynamic behavior that would not have been possible if the SVG content had been simply references by an <img> element as on Day 1.

Excerpt showing SVG content as embedded in the HTML code

[Code not loaded]

JavaScript that changes the color of a random pixel

[Code not loaded]

JavaScript that changes specified pixel

[Code not loaded]

Resources used in this page

Prev Home Next