Internet Explorer 9 sometimes draws blank images on canvas - javascript

I have a web application that generates images on the fly and then renders (segments of) them on the client using canvas - the general code looks something like this (simplified)...
var width = ...
var height = ...
var img = new Image();
img.onload = function(){ // Set onload before setting image source ;)
var canvas = document.createElement("canvas");
canvas.setAttribute('width',width);
canvas.setAttribute('height',height);
var context = canvas.getContext("2d");
context.drawImage(this,0,0,width,height,0,0,width,height);
}
img.src = ...
In firefox and chrome, this works fine. In IE9 (and sometimes IE10), this sometimes results in a blank image. As a workaround, I put in...
var width = ...
var height = ...
var img = new Image();
img.onload = function(){
var canvas = document.createElement("canvas");
canvas.setAttribute('width',width);
canvas.setAttribute('height',height);
var context = canvas.getContext("2d");
window.setTimeout(function(){
context.drawImage(img,0,0,width,height,0,0,width,height);
}, 10); // 10 millisecond delay here seems to give IE time to make sure the image is actually ready
}
img.src = ...
Obviously, putting in random delays is making me nervous - I would much rather figure out why this happens. Is there another event type / method / property on images that may be used? Could there perhaps be something in the http headers sent down with the images / the encoding / transfer method that is causing this?
Since drawing images on the canvas seems to be something that trips up new users a lot, searches mostly yield instances where the developer set the source before the onload method. The closest other question / reply I was able to find was this : https://stackoverflow.com/a/15186350/470062
Edit:
I have updated the examples to include width and height definitions at the start
Edit 29/Apr/2013:
The 10 millisecond delay is not always sufficient - I have changed the code to check the canvas pixels to determine if anything has been drawn - This feels like such an ugly hack though - I would love to know if there is a better way :
... snip - this is at the end of the image load callback..
if((navigator.appVersion.indexOf("MSIE")) >= 0){
function checkAndRedraw(){
context.clearRect(0,0,width,height);
context.drawImage(img, 0, 0, width, height);
var imageData = context.getImageData(0, 0, width, height),
data = imageData.data,
len = data.length;
for (var i = 0; i < len; i += 4){
if(data[i] || data[i+1] || data[i+2]){
scheduleRedraw = null; // prevent memory leak
return; // A pixel contained some non empty value so something was drawn - done.
}
}
scheduleRedraw();
}
var redrawHackTimeout;
function scheduleRedraw(){
window.clearTimeout(redrawHackTimeout);
redrawHackTimeout = window.setTimeout(checkAndRedraw, 500);
}
scheduleRedraw();
}
//END IE9 Hack

I have the same issue in IE9, what I had to do is this too:
theImage = new Image();
theImage.onload = function() {
that = this;
setTimeout(function() {
that.onload2();
}, 100);
};
theImage.onload2 = function(){
#your old load function code
}
theImage.src = 'http://....';
I don't understand why ie9 triggers load image function when it's not actually loaded or not "usable" yet in a canvas. it makes me pull my hair out.

var img = new Image();
img.src = ...
img.onload = function(){ // Set onload before after setting image source ;)
var canvas = document.createElement("canvas");
canvas.setAttribute('width',width);
canvas.setAttribute('height',height);
var context = canvas.getContext("2d");
context.drawImage(this,0,0,width,height,0,0,width,height);
}
You must set the src, then wait for the image to load.

Related

How to synchronously draw an image to a canvas

I have an image encoded in base64 and I need to draw it on a canvas in a synchronous fashion. Take a look at this code I had:
//convert base64 to actual Image()
var input = new Image();
input.src = dataurl;
//draw on canvas
var w = input.width, h = input.height;
canvas.width = w; canvas.height = h;
ctx.drawImage(input, 0, 0)
This used to work on Chrome. I know it is not a good practice to assuming the browser will be able to finish loading before the next instruction, but it worked. After several updates later, it finally fails.
I cannot listen to the load event because that would make it async, which is not good because that's a generator function and I need to return the canvas synchronously. The program is built around it and making it async would mean complete rewrite. That's not good.
Attempt
input.src = dataurl;
while(!input.width){ /* busy wait */ }
var w = input.width, h = input.height;
Does not work since the browser won't update it before my code finishes executing.
Right now I really can't think of any way to solve this dilemma, so any input is appreciated. (Do note that the datauri is generated from another canvas, which I do have access to.)
It's not possible to draw an image to a canvas before it is loaded, which means waiting to a load event. This means you cannot load a data URI into an DOM image synchronously, so you will need to convert your API to an asynchronous one.
The only other way would be to have a JavaScript-based image decoder that converts the data URI into a ImageData object, which would not be trivial to do and require users to load a lot more code.
There used to be a different hack involving innerHTML that would work, but it too no longer works.
Now-Broken Example:
var base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJ4AAACeCAYAAADDhbN7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9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IcADyHAQ4CHAA8hwEOAh1A+Kt1RtIgeDyHAQ4CHEOAhwEMI8BDgIcBDCPAQ4CEEeAjwEAI8BHgIAR4CPIQADwEeAjyEAA8BHkKAhwAPIcBDgIcQ4CHAQwjwEOAhwEMI8FAl9T8BBgB+2d0kUnLhGgAAAABJRU5ErkJggg==';
var el = document.createElement('p');
el.innerHTML = '<img src="'+base64+'" />';
var input = el.firstChild;
//draw on canvas
var canvas = document.getElementById('canvas');
var w = input.width, h = input.height;
canvas.width = w; canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(input, 0, 0);
<canvas id="canvas"></canvas>
Just use Promise to make it async.
return new Promise(resolve => {
image.onload = function () {
ctx.drawImage(input, 0, 0)
resolve('resolved');
}
});

Javascript canvas how to drawImage a lot of images

How i can draw a lot of image in canvas?
I have a lot of images url array and need output it. How to do with good perfomance.
me example code (jsfiddle: http://jsfiddle.net/6sunguw4/):
$(document).ready(function () {
var bgCanvas = document.getElementById("bgCanvas");
var bgCtx = bgCanvas.getContext("2d");
bgCanvas.width = window.innerWidth;
bgCanvas.height = window.innerHeight + 200;
var array = new Array();
array[1] = 'https://developer.chrome.com/webstore/images/calendar.png';
array[2] = 'http://www.w3schools.com/html/html5.gif';
array[3] = 'http://www.linosartele.lt/wp-content/uploads/2014/08/images-9.jpg';
img0 = new Image();
img0.onload = function() {
bgCtx.drawImage(img0, 0,0, 100, 100);
}
img0.src = array[1];
img2 = new Image();
img2.onload = function() {
bgCtx.drawImage(img2, 100,0, 100, 100);
}
img2.src = array[2];
img3 = new Image();
img3.onload = function() {
bgCtx.drawImage(img3, 200,0,100,100);
}
img3.src = array[3];
});
Here's code to load all images from the URLs you put into your array without having to hand code 2000 times new Image/.onload/.drawImage (I call the array imageURLs in the example code below):
// image loader
// put the paths to your images in imageURLs[]
var imageURLs=[];
// push all your image urls!
imageURLs.push('https://developer.chrome.com/webstore/images/calendar.png');
imageURLs.push('http://www.w3schools.com/html/html5.gif');
imageURLs.push('http://www.linosartele.lt/wp-content/uploads/2014/08/images-9.jpg');
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
bgCtx.drawImage(imgs[0], 000,0, 100, 100);
bgCtx.drawImage(imgs[1], 100,0, 100, 100);
bgCtx.drawImage(imgs[2], 200,0, 100, 100);
}
For better loading performance:
Browsers typically download only 6-8 files at a time from one domain. So your 2000 images would require 2000/8 == 250 separate sequential calls to your domain to load.
You can combine your 2000 into one or more spritesheets (preferably 6 or less spritesheets). That way the browser can download the 1-6 spritesheets containing your 2000 images in one trip.
You can use the extended version of context.drawImage to pull any desired image from the spritesheet. For example, assume an image you need is located at [200,200] on your spritesheet and is 100x100 in size. You can draw that image on your canvas like this:
bgCtx.drawImage(spritesheet,
200,200,100,100 // clip the image from the spritesheet at [200,200] with size 100x100
125,250,100,100 // draw the clipped image on the canvas at [125,250]
);
There's not much you can do with the code itself. drawImage seems pretty optimized, and it's the raw amount of images what could slow things down.
One thing you can maybe do, depending on your goal, is to prepare composite images. For example, those 3 images could be easily converted into a single PNG image, and then it would require only one drawImage call. However, if you plan to shift their places or some effects, I'm afraid you're stuck with what you have.

Drawing an image in javascript won't work when vars are global

Hey I want to draw multiple images, one a canvas background, two a player that can move on top of that canvas. Here is my question: When I put the var canvas and canvas properties globally it doesn't work. But when I put it back in the img.onload function it works!!! Why is this and what options do I have?
var canvas = document.getElementById("Canvas");
canvas.width = 500;
canvas.height = 500;
var g = canvas.getContext("2d");
var img = new Image();
img.src = "Images/Grass Texture.png";
var player1 = new Image();
player1.src = "Images/Players/Mignolet.png";
var player2 = new Image();
player2.src = "Images/Players/De Gea.png";
var football = new Image();
football.src = "Images/Football/Football.png";
img.onload = function()
{
/* The rest of the code draws onto the graphics context */
g.drawImage(img, 0, 0);
g.drawImage(img,1200, 1200, 1200, 1200);
};
It's important to understand that image loading is asynchronous. That means while your image is loading the code will continue despite.
If the browser is not able to load and decode the images in time there won't be any images to draw.
Even when you use the onload handler (which is necessary) you need to think about the asynchronous nature in the rest of the code - perhaps the code continues to other parts which will fail due to dependency on the images.
You can collect image loading like this:
...
/// if you have many images an array could be considered
var img = new Image();
var player1 = new Image();
var player2 = new Image();
var football = new Image();
/// number of images to load
var count = 4;
/// now share a load handler
img.onload = loadHandler;
player1.onload = loadHandler;
player2.onload = loadHandler;
football.onload = loadHandler;
/// set sources to start loading
img.src = "Images/Grass Texture.png";
player1.src = "Images/Players/Mignolet.png";
player2.src = "Images/Players/De Gea.png";
football.src = "Images/Football/Football.png";
function loadHandler() {
/// decrement the counter
count--;
/// when 0 all images has loaded
if (count === 0) startGame();
}
When all images has loaded the script will continue to startGame() which is also where you need to continue your game from:
function startGame() {
...
g.drawImage(img, 0, 0);
g.drawImage(img,1200, 1200, 1200, 1200);
/// Important! continue your code from here
nextStep();
}
So after invoking image loading by setting the sources your script does not call any other steps until startGame() is called.
Now, the loading can fail for various reasons. If you don't handle errors your game might just stop and you won't know why. During development you should of course always check the console for errors (see console, network etc. if any errors occur) but for a user this won't help much.
You should always add an error handler mechanism to the images as well. You can do this by using the onerror and onabort handlers - after setting the onload handler:
var hasErrors = false;
img.onerror = errorHandler;
player1.onerror = errorHandler;
player2.onerror = errorHandler;
football.onerror = errorHandler;
img.onabort = errorHandler; /// or use a separate abort handler
player1.onabort = errorHandler;
player2.onabort = errorHandler;
football.onabort = errorHandler;
In the error handler you can notify the user, or use a fallback, or anything that can possible solve the situation:
function errorHandler(err) {
/// set error flag
hasErrors = true;
/// notify user, post an error message etc. something..
console.log('Could not load image:', this.src, err);
/// call loadHandler() from here to decrement counter and
/// handle situation when all images has reported in for duty (or not)
loadHandler();
}
And then modify the loadHandler to be error aware (just an alert here, but replace with something more useful):
function loadHandler() {
/// decrement the counter
count--;
/// when 0 all images has loaded
if (count === 0) {
if (hasErrors) {
alert('Sorry mate! Error during image loading');
return;
}
startGame();
}
}
That being said, you can also do this by using an image loader that can handle all the setup and events (loading, errors, progress etc.) for you. These are made, incl. my own if I may, YAIL loader (and there are others), for the purpose of saving developers from a lot of problems and headache - and they are free. Something to consider..
Hope this helps!

How can I feature test a browser's ability to use video as a canvas source

As some of you might know it's not possible to use HTML5 video as an image source for canvas elements on mobile devices (the video will be opened in an external player instead of the browser). I need a feature test for that.
As I cannot simply check for canvas and video support (as most mobile devices will support both, but not the interaction) I was thinking of doing something like this:
var feature = true;
try {
var v = document.createElement('video');
var c = document.createElement('canvas');
c.getContext('2d').drawImage(v, 0, 0, 100, 100);
} catch (e){
feature = false;
}
alert(feature);
Yet, it will return true on the iPad, Android will output false. I probably assume this is not an iOS Safari bug but a flaw in my feature test, but I simply have no clue of how to approach this.
UPDATE:
So what I ended up with at the moment is the following:
var v = document.createElement('video');
var feature = false;
if (v.canPlayType('video/mp4') == 'probably'){
v.src = 'data:video/mp4;base64,AAAAHGZ0eXBtcDQyAAAAAG1wNDJpc29tYXZjMQAAAz5tb292AAAAbG12aGQAAAAAzaNacc2jWnEAAV+QAAFfkAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAGGlvZHMAAAAAEICAgAcAT////3//AAACQ3RyYWsAAABcdGtoZAAAAAHNo1pxzaNacQAAAAEAAAAAAAFfkAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAEAAAABAAAAAAAd9tZGlhAAAAIG1kaGQAAAAAzaNacc2jWnEAAV+QAAFfkFXEAAAAAAAhaGRscgAAAAAAAAAAdmlkZQAAAAAAA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SlGbu+oiAkcWFbklC6Zhf+NtTLFpn8oWz+HsNRVSgIxZWON+yVyJlE5tq/+GWLTMutYX9ekTySEQPLVNQQ3OfycwJBM0zNtZcse7CvcKI0V/zh16Dr9OSA21MpmmcrHC+6pTAPHPwoit3LHHqs7jhFNRD6W8+EBGoSEoaZttTCZljfduH/fFisn+dRBGAZYtMzbVMwvul/T/crK1NQh8gN0SRRa9cOux6clC0/mDLFpmbarmF8/e6CopeOLCNW6S/IUUg3jJIYiAcDoMcGeRbOvuTPjXR/tyo79LK3kqqkbxkkMRAOB0GODPItnX3Jnxro/25Ud+llbyVVSN4ySGIgHA6DHBnkWzr7kz410f7cqO/Syt5KqpFVJwn6gBEvBM0zNtZcpGOEPiysW8vvRd2R0f7gtjhqUvXL+gWVwHm4XJDBiMpmmZtrLfPwd/IugP5+fKVSysH1EXreFAcEhelGmbbUmZY4Xdo1vQWVnK19P4RuEnbf0gQnR+lDCZlivNM22t1ESmopPIgfT0duOfQrsjgG4tPxli0zJmF5trdL1JDUIUT1ZXSqQDeR4B8mX3TrRro/2McGeUvLtwo6jIEKMkCUXWsLyZROd9P/rFYNtXPBli0z398iVUlVKAjFlY437JXImUTm2r/4ZYtMy61hf16RPJIU9nZ1MABAwAAAAAAAAAZpwgEwIAAABhp658BScAAAAAAADnUFBQXIDGXLhwtttNHDhw5OcpQRMETBEwRPduylKVB0HRdF0A';
}
var c = document.createElement('canvas');
c.width = c.height = 50;
var ctx = c.getContext('2d');
v.play();
var async = setTimeout(function(){
ctx.drawImage(v,0,0);
var data = ctx.getImageData(0, 0, 50, 50).data;
feature = (Math.max.apply(Math, data) > 0);
v.pause();
}, 50);
At least it finally produces the correct output on iOS, yet there are two more problems:
it is async
firefox will (sometimes) fail, complaining about SecurityError: The operation is insecure. at var data = ctx.getImageData(0, 0, 50, 50).data what does not really make sense to me.
Any ideas on that?
You could try using a video which has a certain pixel at a certain area, say a black pixel at the top left corner. Then feed the video into the canvas and load just one frame. Then check if you can retrieve that pixel on the canvas using getImageData.

Javascript: How to load an image, get it's imageData and store it in an array?

I am trying to load an image, get the pixel values out of it and store them in an array for later use. The reason for this is that I'm coding a raycaster("fake 3d" engine), where I want to draw walls as columns on the screen with pixel values taken from a texture-image loaded before-hand.
This is the code im using now:
var imgwidth;
var imgheight;
var wallSprite1 = new Image();
wallSprite1.src = "textures/bricks_tile.gif"
if(wallSprite1.complete) findHHandWW();
else wallSprite1.onload = findHHandWW;
function findHHandWW() {
imgwidth = this.width;
imgheight = this.height;
getImageData(this);
return true;
}
function getImageData(img) {
var tempcanvas = document.createElement('canvas');
tempcanvas.height = imgwidth;
tempcanvas.width = imgheight;
var tempcontext = tempcanvas.getContext("2d");
tempcontext.drawImage(img,0,0);
wallData = tempcontext.getImageData(0, 0, imgwidth, imgheight);
}
However, this gives me the following error:
Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
Uncaught Error: SECURITY_ERR: DOM Exception 18
I read about it, and didn't find any real answer to my problem. I want run this locally, for now. Is it even possible? I tried using;
image.crossOrigin = '';
but it didnt work.
Have I gone about this in the wrong way? I wonder if there's an easier way to accomplish what I want.

Categories