我嘗試了幾次來解決這個問題,但我一直無法找到解決方案,我希望有人能幫助我。我試圖在我的網頁上提供有關影像大小的資訊以稍后實作滾動,這是我的代碼:
ngAfterViewInit() {
let images = [{...document.querySelectorAll('img')}];
this.addImages(images);
}
addImages(images) {
this.imageStore = images.map(img => {
let bounds = img.getBoundingClientRect();
console.log(bounds);
let geometry = new THREE.PlaneBufferGeometry(bounds.width, bounds.height, 1, 1);
let material = new THREE.MeshBasicMaterial({ color: 0xff0000 })
let mesh = new THREE.Mesh(geometry, material)
this.scene.add(mesh);
return {
img: img,
mesh: mesh,
top: bounds.top,
left: bounds.left,
width: bounds.width,
height: bounds.height
}
})
}
該代碼應該回傳我的 HTML 頁面上影像的大小,但我收到了錯誤
uj5u.com熱心網友回復:
ngAfterViewInit() {
const images = Array.from(document.querySelectorAll('img'));
const imgObj = images.map((img) => {
const bounds = img.getBoundingClientRect();
return {
img,
name: img.name,
top: bounds.top,
bottom: bounds.bottom,
left: bounds.left,
width: bounds.width,
height: bounds.height,
};
});
console.log('Applying...');
console.log({ imgObj });
}
https://stackblitz.com/edit/angular-ivy-yeu1hx?file=src/app/app.component.ts
uj5u.com熱心網友回復:
我認為問題在于您需要等待影像加載。
如果您的影像在一個陣列中(有些像)
images=["https://picsum.photos/200/300?random=1",
"https://picsum.photos/200/300?random=2"]
你在 *ngFor 中顯示它,使用事件 (load)
<ng-container *ngFor="let img of images">
<img #mimg [src]="img" (load)="pushData(mimg)">
</ng-container>
array:any[]=[]
pushData(el:any)
{
this.array.push(el.getBoundingClientRect())
if (this.array.length==this.images.length)
{
console.log("all images loaded")
..do something..
}
}
更新,因為我們不知道影像加載的順序,我們可以強制傳遞索引
<ng-container *ngFor="let img of images;let i=index">
<img #mimg [src]="img" (load)="pushData(mimg,i)">
</ng-container>
pushData(el:any,index:number)
{
this.array[index]={
...el.getBoundingClientRect(),
img:el
}
if (!this.array.find(x=>!x))
{
console.log("all images loaded")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343774.html
