I'm trying to use base64 to show an image, BUT it only shows the encoded string but not the image.
I copied it to a new file, and it showed correctly.
This is the code:
@customElement('image-board')
export class ImageBoard extends LitElement {
// ...
@property()
imgSrc = ""
render() {
var img = ""
if (this.imgSrc != "") {
img = `<div> <img src="data:image/png;base64,${this.imgSrc}" /> </div>`;
}
return html`
<div id="image-setter">
${img}
<input type="file" id="imageInput" accept="image/png, image/jpeg" />
<button @click=${this.setImage}>Set Image</button>
</div>
`
}
// ...
}
I use lit
to build my components.
I'm sure that my imgSrc could either be an empty string or a valid base64 encoding image.
I've tried a smaller image (150 x 100 px) but it still could not run correctly.
However, the following is exactly what I want.
But I implement it by adding another img tag out of the component like:
<img id="outside-image"></img>
<image-board></image-board>
and set it's src by
let node = document.getElementById("outside-image");
node.src = `data:image/png;base64,${this.imgSrc}`
I'm confused that why it can not display correctly just by:
img = `<div> <img src="data:image/png;base64,${this.imgSrc}" /> </div>`;
PS: I'm not an English-speaker, so some expressions may not be accurate.
If you wish to render the
img
HTML string, you need to pass it to thehtml
template literal again. For example...See this lit playground demo in action