我无法将此圆形图像保存为 png。
在这里,我将空白画布作为控制台中的基本代码。
任何人请告诉我如何将画布内容(如 rouneded 图像)保存为 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句