JSFiddle - React, Tailwind, and code Playground
by Richard Hunter
HTML
<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>
JavaScript
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;
//fabric.Image.fromURL('img/products/' + articleNumber + '.png', function(oImg) {
fabric.Image.fromURL('https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRlkStdmho9qfM4ofmV4lSVRV_MPmrxPu1f1Q&usqp=CAU', function(oImg) {
console.log('INSIDE CALLBACK VALUE OF i', i);
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);
});
}