I have a preload link in my html.
<link rel="preload" href="sprite.png" id="mySprite" as="image">
How can I convert this to a Image in Javascript?
(let sprite = new Image(myPreloadeImageFromHTML)
I have a lot of images needed, but they do not load on time, which results in no images shown.
How can I preload it and obtain it in Javscript as an Image using a <link rel="preload">?
I have created a link and a canvas in HTML and using javascript I am fetching that link href then created an image from that link and then inserted that image into the canvas.
HTML:
<!-- Your Link -->
<link rel="preload" href="https://www.android-examples.com/wp-content/uploads/2016/03/demo_image.jpg" id="mySprite" as="image">
<!-- Create Canvas -->
<canvas id="my-canvas" />
JS:
var img1 = new Image();
img1.src = document.getElementById("mySprite").href;
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
img1.onload = function () {
c.width = img1.width;
c.height = img1.height;
ctx.drawImage(img1, 0, 0);
}
Here is the reference: https://jsfiddle.net/uLwpsdqt/