Wednesday, 26 July 2017

javascript - Is an event triggered when an HTML link element () containing base64 data as href is ready?

I have created a webpage that basically displays 2 images side by side.



It has a "download" button, which triggers a vanilla Javascript function, which creates a HTML element and concatenates the two images inside of it. It then creates a link with the base64-encoded result image as href and clicks on it:





Here is what the function I'm using looks like:



/** 
* Create canvas, draw both images in it, create a link with the result

* image in base64 in the "href" field, append the link to the document,
* and click on it
*/
function saveImage() {

// Get left image
var imgLeft = new Image();
imgLeft.setAttribute('crossOrigin', 'anonymous');
imgLeft.src = "imgleft/" + idxImageShownLeft + ".jpg";
imgLeft.onload = function() {


// Once the left image is ready, get right image
var imgRight = new Image()
imgRight.setAttribute('crossOrigin', 'anonymous');
imgRight.src = "imgright/" + idxImageShownRight + ".jpg";
imgRight.onload = function() {

// Once the right image is ready, create the canvas
var canv = document.createElement("canvas");
var widthLeft = parseInt(imgLeft.width);

var widthRight = parseInt(imgRight.width);
var width = widthLeft + widthRight;
var height = imgLeft.height;

canv.setAttribute("width", width);
canv.setAttribute("height", height);
canv.setAttribute("id", "myCanvas");
canv.setAttribute('crossOrigin', 'anonymous');
var ctx = canv.getContext("2d");


// Draw both images in canvas
ctx.drawImage(imgLeft, 0, 0);
ctx.drawImage(imgRight, widthLeft, 0);

// Create PNG image out of the canvas
var img = canv.toDataURL("image/png");

// Create link element
var aHref = document.createElement('a');
aHref.href = img;

aHref.setAttribute("id", "dllink");
aHref.download = "image.png";

// Append link to document
var renderDiv = document.getElementById("render");
renderDiv.replaceChild(aHref, document.getElementById("dllink"));

// Click on link
aHref.click();
}

}
}


My problem is that this works fine on Firefox, but not on Chrome.



After a bit of investigating, I realized that by setting a breakpoint before the aHref.click(); line in Chrome, it worked fine. I think that it means that the aHref.click(); is called before the

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...