HTML5 canvas image is not visible in chrome

后端 未结 2 1805
自闭症患者
自闭症患者 2021-01-26 08:34

I am using HTML5 canvas and putting two images there but I am facing one problem which is, one image is loaded and visible in chrome but another image is only visible in mozilla

2条回答
  •  逝去的感伤
    2021-01-26 09:29

    @Rayon's answer is right in that with your current implementation you can't know which image will have loaded first, but IMO it is wrong to wrap everything in the same callback, since you will have to wait for the first image has loaded before trigger the loading of the next one, whcih will produce a flicker apparition of the last image.

    Instead, create a preloader function that will trigger a drawing function when both images have been loaded.

    This has the advantage to make it easier to call your drawing function later, and also to keep your code a bit cleaner :

    /* preloader
      inputs : 
        an array containing the urls of the images to load,
    	a callback function called when all the images have loaded	
      outputs: 
        an array containing all the image elements in the same order has the urls where provided	
    */
    function preloader(imageURLs, callback) {
    
      var toLoad = imageURLs.length,
        toReturn = [],
        decrement = function() {
          if (--toLoad <= 0) {
            callback();
          }
        };
    
      imageURLs.forEach(function(url) {
        var img = new Image()
          // you may want to include a more verbose error function
        img.onload = img.onerror = decrement;
        img.src = url;
        toReturn.push(img);
      });
    
      return toReturn;
    }
    
    function draw() {
      ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
      ctx.drawImage(front, (canvas.width - front.width) / 2, (canvas.height - front.height) / 2);
    }
    
    var ctx = canvas.getContext('2d'),
      urls = [
        'http://img13.deviantart.net/1550/i/2011/353/4/2/mobile_game_background_by_disnie-d4jmr8r.jpg',
        'https://d30y9cdsu7xlg0.cloudfront.net/png/5670-200.png'
      ],
      images = preloader(urls, draw),
      background = images[0],
      front = images[1];

提交回复
热议问题