Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a variable containing `new Image()` in AngularJS ng-repeat?

I have an array that looks like this:

var imageList = [ image1, image2, image3 ];

Each element in this array is a variable containing new Image(). For example: var image1 = new Image().

I preload each image using .onload event for each element after setting its url. Only after all the images have been loaded, that anything else can happen.

How do I output each array element in AngularJS and show the image?

<li ng-repeat="image in imageList">
   {{ image }}
   /* I want the expected output of the above line to look like
      <img src="./img/xx.svg" /> */
</li>

I don't want to do anything like the code below since I already created each element in the array as a new Image():

<li ng-repeat="image in someImageList">
   <img ng-src="{{ image.url }}" />
</li>

The current output if I do {{ image }} is just list of {}. If use just image, the output is a list of "image" string.

The reasons why I'm creating new image elements using JavaScript instead of using the <img/> tag are that 1. I need to preload the images and 2. I need to draw these images in <canvas>. It's redundant to create <img/> for the same image sources. Also, it makes opening for a modal that shows a list of these images very slow to open. So if the images are preloaded already, the modal might open faster.

like image 357
junerockwell Avatar asked Aug 09 '26 12:08

junerockwell


1 Answers

You will need to convert the image to a data uri and save that string.

$scope.images = [];

loadImage('./img/xx.svg');

function loadImage(src) {
  var img = new Image();

  img.onload = function() {
    // Create a canvas
    var canvas = document.createElement('canvas');

    // Be sure the canvas is the same size as your image
    canvas.width = this.width;
    canvas.height = this.height;

    // Draw the image to the canvas
    canvas.getContext('2d').drawImage(this, 0, 0);

    // Add the data uri to your scope
    $scope.images.push(canvas.toDataURL('image/png'));

    // "Notify" Angular something has changed
    $scope.$apply();
  }

  img.src = src;
}

Then you can print it like this-

<li ng-repeat="image in images">
   <img ng-src="{{ image }}" />
</li>

Image will be the data uri (not a url).

How you implement this with the canvas is up to you.

like image 162
micah Avatar answered Aug 12 '26 10:08

micah