Skip to content Skip to sidebar Skip to footer

How To Get The Right Image Data In Base64 Format Using Html5 Canvas

I'm trying to crop a image using ctx.drawImage() and get the cropped image data using canvas.toDataURL(). However I can't get the right data until I refresh the page few times. I w

Solution 1:

You need to wait for your image to be loaded. Use the onload event.

The reason it works after a few times is because the browser caches it, and makes it load before you run your toDataURL code.

For example, your code would look like this:

var imageObj = newImage();
imageObj.src = 'http://localhost:63342/war/img/IMG_20140131_102234.jpg';
var canvas = document.createElement('canvas');
canvas.width = 30;
canvas.height = 30;

// Copy the image contents to the canvasvar ctx = canvas.getContext("2d");
imageObj.addEventListener('load', function () {
    ctx.drawImage(imageObj, 0, 0, 715, 715, 0, 0, 30, 30);

    // Get the data-URL formatted imagevar dataURL = canvas.toDataURL("image/png");
    console.log(dataURL);
});

Post a Comment for "How To Get The Right Image Data In Base64 Format Using Html5 Canvas"