gpt4 book ai didi

javascript - 如何在 AngularJS ng-repeat 中呈现包含 `new Image()` 的变量?

转载 作者:行者123 更新时间:2023-11-29 14:44:04 24 4
gpt4 key购买 nike

我有一个如下所示的数组:

var imageList = [ image1, image2, image3 ];

此数组中的每个元素都是一个包含new Image() 的变量.例如:var image1 = new Image() .

我使用 .onload 预加载每个图像设置其 url 后每个元素的事件。只有在加载完所有图像后,才能发生其他任何事情。

如何在 AngularJS 中输出每个数组元素并显示图像?

<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>

我不想像下面的代码那样做任何事情,因为我已经将数组中的每个元素创建为一个新的 Image():

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

如果我这样做的当前输出 {{ image }}只是 {} 的列表。如果只使用 image ,输出是一个“图像”字符串列表。

我使用 JavaScript 而不是使用 <img/> 创建新图像元素的原因标签是 1. 我需要预加载图像和 2. 我需要在 <canvas> 中绘制这些图像.创建 <img/> 是多余的对于相同的图像源。此外,它使显示这些图像列表的模态的打开速度非常慢。因此,如果图像已经预加载,模态可能打开得更快。

最佳答案

您需要将图像转换为数据 uri 并保存该字符串。

$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;
}

然后你可以像这样打印它-

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

图像将是数据 uri(不是 url)。

如何使用 Canvas 实现它取决于您。

关于javascript - 如何在 AngularJS ng-repeat 中呈现包含 `new Image()` 的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34800491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com