I have this issue with a script that I was developing, to upload images on a canvas and with the cursor make it pass like a carousel
VM20:158 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
at draw (<anonymous>:158:57)
when I go to the line that is pointing the problem
if (imgArray.length == sprite.cols * sprite.rows) {
ctx.drawImage(imgArray[ci], 0, 0);
}
but when I re-do it for the second time (that means pressing F5 and uploading the images again) it works
the code that is being skipped in the first time is
function showFile() {
var fileInput = document.querySelector('input[type=file]');
for (var i = 0; i < fileInput.files.length; i++) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
var listItem = document.createElement('li');
imagenes.push(readerEvent.target.result);
image_load = 'si';
};
reader.readAsDataURL(fileInput.files[i]);
}
}
The question is: why it works only when i re-do the process again and not at the first time?.
Source on Google sites
https://sites.google.com/view/pruebamodelado/home
the pictures are at https://sites.google.com/view/pruebamodelado/fotos-test-downlaod?authuser=0
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
imagenes.push(img.src);
image_load="si"
}
You're creating a race condition here, and also pushing the src
string to the array instead of the image. Before an image can be drawn to a canvas it has to be loaded, and you're not listening to the load event. The outcome is that sometimes the images have had enough time to load, and sometimes they did not, causing the error. It can work the second time because your browser is probably caching the images and they load faster. You can solve it like this:
reader.onload = function (e) {
var img = document.createElement("IMG");
img.onload = () => {
imagenes.push(img);
image_load="si"
}
img.src = e.target.result;
}
EDIT: Now I see that you're creating another Image
instance from the src later in the code, but the same problem happens there as well - you need to listen to the load
event before you can draw it on a canvas.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.