I attempted to achieve a similar effect (inspired by Fabio Ottaviani) as shown in this CodePen.
However, I'm facing the challenge of creating this SVG using JavaScript.
The ChatGPT response seems correct. The SVG is generated in the DOM but doesn't display on the screen.
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Creating SVG with JavaScript</title>
</head>
<body>
<script>
// Function to create an SVG element with specified attributes
function createSVGElement(tag, attributes) {
const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const key in attributes) {
element.setAttribute(key, attributes[key]);
}
return element;
}
// Creating a circle with the "displacement" class
const circleMask = createSVGElement("circle", {
cx: "200",
cy: "200",
r: "100",
fill: "white",
class: "displacement",
});
// Creating the image
const image = createSVGElement("image", {
"xlink:href": "https://images.unsplash.com/photo-1630563451961-ac2ff27616ab?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MTF8fGFwcGxlfGVufDB8fDB8fHww&auto=format&fit=crop&w=400&h=400&q=60",
width: "400",
height: "400",
mask: "url(#circleMask)",
});
// Creating the mask and adding the circle
const mask = createSVGElement("mask", { id: "circleMask" });
mask.appendChild(circleMask);
// Creating the <defs> element and adding the mask
const defs = createSVGElement("defs");
defs.appendChild(mask);
// Creating the SVG and adding the elements above
const svgElement = createSVGElement("svg", {
width: "400",
height: "400",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
});
svgElement.appendChild(defs);
svgElement.appendChild(image);
// Adding SVG to the body
document.body.appendChild(svgElement);
</script>
</body>
</html>;
</script>
</body>
</html>
I've tried :
image.addEventListener("load", function () {
svgElement.appendChild(image);
document.body.appendChild(svgElement);
});
In an attempt to wait for the image to load...
Additionally, I've also tried:
document.addEventListener("DOMContentLoaded", function () {
document.body.appendChild(svgElement);
});
Unfortunately, none of these methods yielded any results :(
Although the SVG appears in the DOM when inspected, everything seems fine, yet it doesn't display as intended. Here's a screenshot from the browser showing the issue.
I have ruled out the common mistake of using document.createElement
. Any thoughts or ideas?