So I am in the middle of a project and needed to paste some pixelart icons I made in asesprite into my HTML. I tried it with an img-tag at first but it became blurry, so I found this website and got the idea of making a general function wich I could use on several images and canvases. Then I made this function:
const pasteOnCanvas = (imageSource, canvasID) => {
const canvas = document.querySelector('#' + canvasID);
const context = canvas.getContext('2d');
base_image = new Image();
base_image.src = imageSource;
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
pasteOnCanvas("images/heart_icon.png", "hp-icon");
pasteOnCanvas("images/sword_icon.png", "attack-icon");
It does work on one canvas, but when you call the function several times it just pastes the last image on every canvas. Is there any way to fix this so that it works?
Here is my HTML code:
<canvas id="hp-icon" class="pixelart-image" width="16" height="16"></canvas>
<canvas id="attack-icon" class="pixelart-image" width="16" height="16"></canvas>
And my CSS:
.pixelart-image {
height: 128px;
width: 128px;
image-rendering: crisp-edges;
image-rendering: pixelated;
}