I am trying to create an array of patterns to use for my Chart.js doughnut chart so I do this:
var surfacePatterns;
var surfaceNames = ['Unknown', 'Paved', 'Unpaved', 'Concrete', 'Cobblestone', 'Metal', 'Wood', 'Ground', 'Sand', 'Grass'];
$(document).ready(() => {
surfacePatterns = [];
console.log(surfacePatterns);
for (i = 0; i < surfaceNames.length; i++) {
var temp = new Image();
temp.onload = () => surfacePatterns.push($("#canvas1")[0].getContext('2d').createPattern(temp, 'repeat'));
temp.src = '../img/surfaces/'+ surfaceNames[i] + '.jpg';
}
});
function chart(){
console.log(surfacePatterns);
}
The chart() function is called by a button press. I deliberately wait for a few seconds so it can load the images and create the patterns but when I call the function it gives me this:
Out of the nine images only 8 and 9 got converted into a pattern and the rest is null. I have no idea what's going on because I get no errors and all images are found. If I change a String in surfaceNames I, as expected, get an error that an image couldn't be found and if I use patterns 8 and 9 they work perfectly fine.
Another weird thing: If I change
temp.onload = () => surfacePatterns.push($("#canvas1")[0].getContext('2d').createPattern(temp, 'repeat'));
to
temp.onload = () => surfacePatterns[i] = canvas1[0].getContext('2d').createPattern(temp, 'repeat');
the entire array is completely empty (=/= null). Also the first log after initializing the array as an empty array gives me an empty array with a length of 9 and I have no idea why since nothing else has happened yet.
I have a limited JavaScript understanding so I would be thankful for every tip on why this is happening.
from Creating multiple canvas patterns fails

No comments:
Post a Comment