1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
有一個(gè)非常簡(jiǎn)單的解決方法可以解決您的問(wèn)題,那就是使用let
而不是在您的語(yǔ)句中var
聲明。i
for
for?(let?i?=?0;?i?<?allproducts.length;?i++)?{?? ??//?...}
問(wèn)題在于,在對(duì) 的所有回調(diào)中fromURL
, 的值i
停留在 for 循環(huán)完成時(shí)的最后一個(gè)值。這是因?yàn)楫?dāng)您用 聲明i
變量時(shí)var
,它的范圍不僅在 for 循環(huán)內(nèi),而且在整個(gè)包含函數(shù)中。因此只有一個(gè)i
變量由所有回調(diào)共享,并且由于它們都在循環(huán)完成后運(yùn)行,因此它們會(huì)獲得最后一個(gè)值i
。如果您在回調(diào)中放置一個(gè) console.log,您會(huì)發(fā)現(xiàn)情況確實(shí)如此。
let
另一方面,當(dāng)您使用 時(shí),i
會(huì)為 for 循環(huán)的每次迭代創(chuàng)建一個(gè)新變量。這是因?yàn)?code>let具有塊作用域并且 for 循環(huán)是一個(gè)塊。因此,每個(gè)回調(diào)都有自己唯一且正確的 值i
。
這是您的代碼的工作版本:
const allproducts = [1, 2, 3, 4];
var canvas = new fabric.Canvas('foo');
for (let i = 0; i < allproducts.length; i++) {
? // Product image
? var articleNumber = allproducts[i];
? const fullHeight = 1000;
? const fullWidth = 500;
? const imageUrl = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRlkStdmho9qfM4ofmV4lSVRV_MPmrxPu1f1Q&usqp=CAU';
? fabric.Image.fromURL(imageUrl, function(oImg) {
? ? oImg.scaleToHeight(fullHeight / 10)
? ? ? .set('originX', 'center')
? ? ? .set('left', Math.floor(Math.random() * fullWidth))
? ? ? .set('top', Math.floor(Math.random() * (fullHeight - 200)))
? ? // Article Number
? ? var text = new fabric.Text('? ' + allproducts[i] + '? ', {
? ? ? left: oImg.left,
? ? ? top: oImg.top + fullHeight / 10 + 2,
? ? ? originX: 'center',
? ? ? fontSize: 9,
? ? ? fontFamily: 'Helvetica',
? ? ? textAlign: 'center',
? ? ? backgroundColor: 'white'
? ? });
? ? // Grouped Article number and Product Image
? ? var product = new fabric.Group([oImg, text], {
? ? ? hasControls: false,
? ? });
? ? // Add Product to Canvas
? ? canvas.add(product);
? });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.1.0/fabric.min.js"></script>
<canvas id="foo" width="1200" height="1200"></canvas>
添加回答
舉報(bào)