Preload images that will be drawn on fabric.js canvas

2.2k views Asked by At

Hello I'm building a website where I display images on fabric canvas by hovering over text content on the site. There are many text links connected to many different images. There is always only one image on the canvas being displayed, but there are many in the 'bank'. At every hover call I change the source parameter of Fabric.js image object. Also the image itself is never part of the DOM.

My problem is that when the page loads and user hovers over the link it takes at least two 'hovers', meaning that the user has to enter and leave the text link area at least twice, to actually display the image.

First hover-over downloads the image, and when the image is loaded the second hover-over displays it.

Is there any way how to preload these images so they would pop up on the very first hover?

I'm using Fabric.js image object.

this is how I display the first image.

fabric.Image.fromURL(source, function(img) {

        cnvs.add(img);
});

and this is how I change the source parameter

    function changeImage(new_img_source) {
        var tmp=cnvs.item(0).getElement();
        var src = tmp.src;      

        tmp.setAttribute("src", img_source); 

        cnvs.renderAll();
    };

and this is Jquery that fires the changeImage()

    function emphasize(target, img_source) {

        $(target).hover( function() {
            changeImage(img_source);
        });
    };
1

There are 1 answers

0
markE On BEST ANSWER

Step#1: Preload all your images before the app begins:

How do image preloaders work?

Step#2: when needed, change the image that FabricJS is using for the img object.

 // given you have preloaded images into the imgs[] array
 // load img[1] into the fabricJS img object
 img.setElement( imgs[1]; );
 canvas.renderAll();