2

Can I convert an image to canvas, and vice-versa, with Javascript?

I would like to convert the image to canvas, draw something on the canvas, and then convert the canvas back to an image again.

var canvas = document.getElementById("CANVAS"),
    img    = new Image();

    img.src = canvas.toDataURL();    //=> Error is occurred at this point.
    img.onload = function(){
        // ...
    };

When I convert the canvas to an image, it fails.

SecurityError: The operation is insecure.

The picture is being served from a server.

Is the way wrong? Is it impossible?

4

1 回答 1

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
};
于 2013-07-02T23:00:03.607 回答