0

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/

Rob
  • 14,746
  • 28
  • 47
  • 65
David Hope
  • 1,426
  • 4
  • 21
  • 50
  • You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data. – Mr Zach Dec 03 '17 at 20:25
  • @MrZach, I have tried that. But I can't make it work: https://jsfiddle.net/3p3e6Ldu/3/ – David Hope Dec 03 '17 at 20:29
  • The `if( count == 2 )` section in your example has to be inside the `onload` callbacks. You should familiarize yourself with async coding! – Sirko Dec 03 '17 at 20:59
  • @Sirko, I have tried that too. it didn't work. did you try your suggestion? – David Hope Dec 03 '17 at 21:00

1 Answers1

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) );
lolol
  • 4,287
  • 3
  • 35
  • 54
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything. – David Hope Dec 03 '17 at 21:50