javascript - 无法获取内容的画布 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);
解决方案
在尝试使用它之前,您需要等待图像加载。
最重要的是,您不能调用受污染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>
推荐阅读
- c# - 使用用户的原始输入每 2 秒执行一次主要方法
- c# - 如何修复此语句以增加指定变量?
- powershell - PowerShell 能否区分其执行方式?(计划任务-vs-控制台)
- git - Git 合并 master 到分支并接受部分更改
- typescript - vue-cli-service 无法使用 *.vue 中的自定义别名解析导入
- javascript - 如何为 Range 添加 onKeyDown 事件?
- r - 侧边栏页面未在闪亮的仪表板中打开
- python - 定制的 Jupyter 笔记本
- ruby - 为什么我的循环继续超过它的限制?
- reactive-programming - 如果找到值但不执行其他步骤,则返回 Mono.empty()