简体   繁体   中英

How to wait for the multiple images to load in the canvas and convert to base64?

I'm trying to get a base64 version of a canvas in HTML5.

Currently, the base64 image that I get from the canvas is blank.

I have found similar questions for example this one:

HTML Canvas image to Base64 problem

However, the issue that I have is that because I am adding 2 images in the canvas, I cannot use the example provided in those answers as most of them are using single image.

I understand that I have to wait until the canvas image is loaded properly before trying to get the base64 image. But I don't know how in my case.

This is my code:

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.canvas.width = 1000; context.canvas.height = 1000; var imageObj1 = new Image(); imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"; imageObj1.onload = function() { context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height); }; var imageObj2 = new Image(); imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg" imageObj2.onload = function() { context.drawImage(imageObj2, 0, 0, canvas.width, 180); }; // get png data url //var pngUrl = canvas.toDataURL(); var pngUrl = canvas.toDataURL('image/png'); // get jpeg data url var jpegUrl = canvas.toDataURL('image/jpeg'); $('#base').val(pngUrl); 
  <div class="contents" style="overflow-x:hidden; overflow-y:scroll;"> <div style="width:100%; height:90%;"> <canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas> </div> </div> <p> This is the base64 image </p> <textarea id="base"> </textarea> 

and this is a working FIDDLE:

https://jsfiddle.net/3p3e6Ldu/1/

Can someone please advice on this issue?

Thanks in advance.

EDIT:

As suggested in the comments bellow, i tried to use a counter and when the counter reaches a specific number, I convert the canvas to base64.

Like so: https://jsfiddle.net/3p3e6Ldu/4/

In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand. In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.

However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.

I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle , you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.

A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;

// function to retrieve an image
function loadImage(url) {
  return new Promise((fulfill, reject) => {
    let imageObj = new Image();
    imageObj.onload = () => fulfill(imageObj);
    imageObj.src = url;
  });
}

// get images
Promise.all([
    loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
    loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
  ])
  .then((images) => {
    // draw images to canvas
    context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
    context.drawImage(images[1], 0, 0, canvas.width, 180);

    // export to png/jpg
    const pngUrl = canvas.toDataURL('image/png');
    const jpegUrl = canvas.toDataURL('image/jpeg');

    // show in textarea
    $('#base').val(pngUrl);
  })
  .catch( (e) => alert(e) );

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM