alwaysVBNET alwaysVBNET - 1 month ago 4x
Javascript Question

Getting image from video and adding to canvas works only if alert is added

I am trying to set an image to a canvas for each video. I'm looping through an array of FileIDs and then trying to get an image from the corresponding video and add it on the canvas.

The following code works if an alert is added just before the


The loop:

jQuery.each(arUniqueVideos, function (index, value) {

The function:

function SetThumbnail(value) {
var canvas = jQuery("#img" + value);
var video = jQuery("#vid" + value);
var img = new Image();
img = video[0];
var canv = canvas[0];
//alert('test'); //works only if this alert is added
canv.getContext("2d").drawImage(img, 0, 0, 100, 100);

I have tried to draw the image like this but it still doesn't work:

img.onload = function() {
canv.getContext("2d").drawImage(img, 0, 0, 100, 100);


You need to listen to the load events. oncanplay will fire when the video can play. Adding the alert just allows the video to load before you try to use it. Without the alert your code runs before the video has loaded.

A list of media events