我可以使用Javascript将图像转换为画布,反之亦然吗?
我想将图像转换为画布,在画布上绘制一些东西,然后再将画布转换回图像。
var canvas = document.getElementById("CANVAS"),
img = new Image();
img.src = canvas.toDataURL(); //=> Error is occurred at this point.
img.onload = function(){
// ...
};
当我将画布转换为图像时,它会失败。
SecurityError:操作不安全。
图片是从服务器提供的。
出错了吗?这不可能吗?
答案 0 :(得分:3)
问题解决了。谢谢你的破坏。
的的.htaccess 强> 的
Header set Access-Control-Allow-Origin http://mysite-domain #=> The point of solution
的的javascript 强> 的
将图像转换为画布
this.imageToCanvas = function()
{
var self = this,
img = new Image();
img.src = document.getElementById("IMAGE").src;
img.crossOrigin = "anonymous"; //=> The point of solution
img.onload = function(){
var canvas = document.getElementById("CANVAS");
if ( ! canvas || ! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
self.draw();
};
};
在画布上画一些东西
this.draw = function()
{
var self = this,
text = "stackoverflow",
img = new Image();
img.crossOrigin = "anonymous"; //=> The point of solution
img.src = document.getElementById("SECOND-IMAGE").src;
img.onload = function(){
var canvas = document.getElementById("CANVAS");
if ( ! canvas || ! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 10, 10, img.width, img.height);
ctx.save();
ctx.font = "italic bold 32px 'Times New Roman'";;
ctx.fillStyle = "#0067ef";
ctx.fillText(text, 50, 50);
ctx.restore();
self.canvasToImage(canvas);
};
};
将画布再次转换回图像
this.canvasToImage = function(_canvas)
{
var img = new Image();
img.id = "IMAGE";
img.src = _canvas.toDataURL(); //=> It succeeds this time.
$("#" + _canvas.id).replaceWith(img); //=> with jQuery
};