Mayank S. Gupta
Mayank S. Gupta

Reputation: 69

Unable to get canvas toDataURL of content

I am unable to save this rounded image as png.

Here I am getting blank canvas as base code in console.

Anyone Please tell Me how can I save canvas content like rouneded image as an png or base 64 code.

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');



// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {

// Save the state, so we can undo the clipping
ctx.save();


// Create a circle
ctx.beginPath();
ctx.arc(106, 77, 74, 0, Math.PI * 2, false);

// Clip to the current path
ctx.clip();


ctx.drawImage(img, 0, 0);

// Undo the clipping
ctx.restore();
}

// Specify the src to load the image
img.src = "http://i.imgur.com/gwlPu.jpg";

var base = canvas.toDataURL();
console.log(base);

Upvotes: 0

Views: 881

Answers (1)

user128511
user128511

Reputation:

You need to wait for the image to load before trying to use it.

On top of that you can't call toDataURL on tainted canvases. Tainted canvases are canvases that have had images drawn in them from other domains unless you both request permission to use the image AND the server gives you permission to use the image.

For your example imgur's servers usually give permission. To request permission you need to set img.crossOrigin. See: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');



// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {

  // Save the state, so we can undo the clipping
  ctx.save();


  // Create a circle
  ctx.beginPath();
  ctx.arc(106, 77, 74, 0, Math.PI * 2, false);

  // Clip to the current path
  ctx.clip();


  ctx.drawImage(img, 0, 0);

  // Undo the clipping
  ctx.restore();
  
  var base = canvas.toDataURL();
  console.log(base);
}

// Specify we want to ask the server for permission to use this image
img.crossOrigin = "anonymous";

// Specify the src to load the image
img.src = "http://i.imgur.com/gwlPu.jpg";
<canvas id="c"></canvas>

Upvotes: 2

Related Questions