score:1
You need to wait for all of the patterns to load before you can log the array. In fact, the array should be the result of awaiting all the patterns, rather than a variable in the outer scope that you populate asynchronously. See Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
As for how to solve this, you can use Promise.all()
after converting each callback into a pending promise:
const surfaceNames = ['stackoverflow.com', 'codegolf.stackexchange.com', 'superuser.com', 'codereview.stackexchange.com'];
const context = document.querySelector('#canvas1').getContext('2d');
const promises = surfaceNames.map(surfaceName =>
new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener('load', () => {
resolve(context.createPattern(image, 'repeat'));
});
image.addEventListener('error', () => {
reject(new Error(`${surfaceName} failed to load ${image.src}`));
});
image.src = `https://${surfaceName}/favicon.ico`;
}).catch(error => {
// populating array with null entry and logging error
// instead of ignoring all the other pending promises
console.log(error.message);
return null;
})
);
Promise.all(promises).then(surfacePatterns => {
console.log(surfacePatterns.map(pattern => pattern.constructor.name));
});
<canvas id="canvas1"></canvas>
As you can see, each of these successfully resolves with a CanvasPattern
.
score:0
When calling an async function several times in this case inside a "for", you have to wait for all the calls. If you don't wait they you lost some async calls and you got an empty array.
If you can put a snipped I'll try to fix that problem.
window.surfacePatterns = [];
window.c = 0;
//window.surfaceNames = ['Unknown', 'Paved', 'Unpaved', 'Concrete', 'Cobblestone', 'Metal', 'Wood', 'Ground', 'Sand', 'Grass'];
window.surfaceNames = ["https://www.worldatlas.com/r/w1200-h630-c1200x630/upload/37/99/85/northern-pygmy-owl.jpg",
"https://www.friendsofwehr.org/wp-content/uploads/2013/06/Great-horned_Owl_RWD_at_CRC1transparent.jpg"
];
$(document).ready(() => {
console.log('Step 1: ', window.surfacePatterns);
for (i = 0; i < window.surfaceNames.length; i++) {
var temp = new Image();
temp.onload = function() {
var my = $(".canvas1")[0].getContext('2d').createPattern(temp, 'repeat');
console.log('Step inside async: ', my);
window.surfacePatterns.push(my);
window.c++;
if (window.surfaceNames.length === c) {
console.log('Complete async calls: ', window.surfacePatterns);
}
}
//temp.src = '../img/surfaces/'+ window.surfaceNames[i] + '.jpg';
temp.src = "https://www.friendsofwehr.org/wp-content/uploads/2013/06/Great-horned_Owl_RWD_at_CRC1transparent.jpg"
}
console.log('Outside For: ', window.surfacePatterns);
});
function chart() {
console.log(window.surfacePatterns);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas class="canvas1"></canvas>
<canvas class="canvas1"></canvas>
Source: stackoverflow.com
Related Query
- Creating multiple canvas patterns fails
- Creating dropdown options with Chart.js using select tag and multiple canvas
- how to not repeat code while creating multiple charts in chart js
- Chart.js - Multiple Doughnut Charts on same Canvas
- Chart.js - Creating multiple charts on one page
- Chart.js creating multiple Charts in Angular in same Component
- Ionic using multiple chart.js canvas in the same page
- React render function preventing creating new canvas element on each time invoked - Charts.js
- Can't render multiple responsive canvas graphs in different tabs
- Is it possible to combine multiple charts in one canvas in chartjs?
- Creating multiple charts based on dictionary length
- How to run Chart.js samples using source code
- Creating multiple charts and selecting them later
- Angular Chart.js Multiple Canvas
- How to clear a chart from a canvas so that hover events cannot be triggered?
- Chart.js canvas resize
- Charts.js graph not scaling to canvas size
- Converting Chart.js canvas chart to image using .toDataUrl() results in blank image
- How to add labels into Chart.js canvas plugin?
- Chart.js creating a line graph using dates
- Why is chart.js canvas not respecting the padding of the container element?
- Truncating canvas labels in ChartJS while keeping the full label value in the tooltips
- Chartjs v2 - format tooltip for multiple data sets (bar and line)
- how to plot multiple time series in chartjs where each time series has different times
- Resize chart.js canvas for printing
- Page with multiple chart.js charts to pdf
- Canvas static height Chartjs
- ChartJS canvas not displaying rgba colors in IE, Safari and Firefox
- Chart.js padding canvas
- chartjs tooltip is cut off when out of canvas
More Query from same tag
- chart.js coffeescript can't find variable
- Chart.js maxBarThickness is deprecated in angular 8
- How to display the more then one value inside tooltip in bar chart.js?
- How to add Chart.js to Wagtail Homepage panels using construct_homepage_panels hook?
- How to correctly transform data for a stack chart chartJS (data transformation)?
- Angular chart how to show the legend data value by default along with legend name
- How to display "%" sign on mouse hover in Pie-Chart
- how to display chart.js legend with different bar color
- TypeError: Cannot read property 'length' of null in react component
- Chartjs line chart gets all scrambled up when an x value coincides with a label
- Chart.js - Uncaught ReferenceError: chart is not defined
- Adding text inside 2 different Doughuts chartjs
- How to make Laravel Charts
- How to draw one line with different colors in chartjs2?
- JavaScript doughnut chart with centered hover label
- Chart JS not showing all data
- Chart not displaying from JSON data
- Chart.js version 2.2.1 wont show chart
- ChartJS in Datatable cell performance
- How to set Custom tooltip event with Chartjs version 2.X
- Why wont the json_encoded data show
- how to remove duplicate data set labels in chartjs
- ChartJS showing old values when mouse over on Doughnut after updating values
- How can I keep label string length from affecting size of a Polar Area chart?
- Counting string to plot a graph using chart.js and angular
- chartJS, how to disable user from clicking on legend names and changing the graph?
- Chart.js bar chart : Grid color and hide label
- How to compare one value to another in chartJS
- Streaming Real-time data with react and chartjs-plugin-streaming paused
- load a graph with chart.js and react