首页 > 解决方案 > 无法获取内容的画布 toDataURL

问题描述

我无法将此圆形图像保存为 png。

在这里,我将空白画布作为控制台中的基本代码。

任何人请告诉我如何将画布内容(如圆形图像)保存为 png 或 base 64 代码。

// 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);

标签: javascripthtmlcanvas

解决方案


在尝试使用它之前,您需要等待图像加载。

最重要的是,您不能调用受污染toDataURL的画布。受污染的画布是从其他域中绘制了图像的画布,除非您都请求使用该图像的权限并且服务器允许您使用该图像。

对于您的示例,imgur 的服务器通常会给予许可。要请求权限,您需要设置img.crossOrigin. 请参阅: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>


推荐阅读