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?

Jarrod
  • 9,349
  • 5
  • 58
  • 73
R.Atim
  • 367
  • 1
  • 7
  • 16

1 Answers1

3

The problem was resolved. Thank you for dystroy.

.htaccess

Header set Access-Control-Allow-Origin http://mysite-domain #=> The point of solution 

javascript

convert the image to canvas

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();
        };
};

draw something on the canvas

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);
        };
};

convert the canvas back to an image again

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
};
R.Atim
  • 367
  • 1
  • 7
  • 16
  • Please mark your answer as accepted. Even if it's a duplicate it will be cleaner. And +1 for the effort to build a clean answer gathering the elements, this might help other users. – Denys Séguret Jul 04 '13 at 07:11
  • It seems that it cannot accept now. I will accept if time passes. Thank you. – R.Atim Jul 04 '13 at 12:51