I'm working on a super simplified avatar editor.
I want the user to be able to drag and drop a memoji on top of a background and display the result (then I'll make it downloadable)
I use an svg as the main container, and use an element to display the background png.
On drop of an image, I get a data-url representation of the dropped image and set it as href of a new <image> element. Unfortunately this element never shows up on screen, even though it is there when I inspect my svg element with developer tools.
How to get the dynamically created element to display in my svg?
<!DOCTYPE html>
<html lang="en">
<body>
<svg
id="canvas"
width="800px"
height="800px"
>
<image href="https://cdn.glitch.com/f408a86f-811f-4c06-8c4b-86f559d391b1%2Fbackground.png?v=1631718789960" height="800px" width="800px"/>
</svg>
<script>
const canvas = document.getElementById("canvas");
// Image file reader
const reader = new FileReader();
reader.onload = function() {
const memojiImage = document.createElement("image");
memojiImage.setAttribute("href", reader.result);
memojiImage.setAttribute("height", "844px");
memojiImage.setAttribute("width", "844px");
canvas.appendChild(memojiImage);
};
// Drag and drop
const preventDefault = e => {
e.preventDefault();
e.stopPropagation();
};
canvas.addEventListener("dragenter", preventDefault, false);
canvas.addEventListener("dragleave", preventDefault, false);
canvas.addEventListener("dragover", preventDefault, false);
canvas.addEventListener("drop", preventDefault, false);
canvas.addEventListener("drop", e => {
const file = e.dataTransfer.files[0];
reader.readAsDataURL(file);
});
</script>
</body>
</html>