我正在尝试使用canvas动态裁剪图像并获取base64字符串以加载到元素中。我正在处理来自this post的示例,但是当我运行.toDataURL()时,我得到的base64被截断并且无效。
我的jsfiddle
var image = new Image(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
image.onload = function(){
ctx.drawImage(image,
70, 20, // Start at 70/20 pixels from the left and the top of the image (crop),
50, 50, // "Get" a `50 * 50` (w * h) area from the source image (crop),
0, 0, // Place the result at 0, 0 in the canvas,
50, 50); // With as width / height: 100 * 100 (scale)
}
image.src = 'https://www.google.nl/images/srpr/logo3w.png';
var _img = document.getElementById('base64');
_img.innerHTML += canvas.toDataURL();
从toDataURL我只获得552个base64字符。当我保存裁剪的图像并将图像解码为base64时,它大约是3.8k个字符。
我无法看到我做错了什么 - 有什么想法吗?
答案 0 :(得分:-1)
所以,像往常一样,在我公开发布之前,我没有顿悟。去图。
两个问题
一旦修复,我就收到了错误
可能无法导出受污染的画布。
我修复了(使用imgur上托管的不同图片 - 谷歌图片仍然引发错误)添加
image.setAttribute('crossOrigin', 'anonymous');
更正后的代码:
var image = new Image(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function(){
ctx.drawImage(image,
70, 20, // Start at 70/20 pixels from the left and the top of the image (crop),
50, 50, // "Get" a `50 * 50` (w * h) area from the source image (crop),
0, 0, // Place the result at 0, 0 in the canvas,
50, 50); // With as width / height: 100 * 100 (scale)
var _img = document.getElementById('base64');
_img.innerHTML += canvas.toDataURL();
}
image.src = 'https://www.google.nl/images/srpr/logo3w.png';