Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put text on an image and save as image

I have one problem with HTML5 Canvas. I have one image. On this image I want to put text and display/save this as an image.

I have this code:

window.onload = function(){
 var canvas = document.getElementById("myCanvas");
 var context = canvas.getContext("2d");
 var imageObj = new Image();
 imageObj.onload = function(){
     context.drawImage(imageObj, 10, 10);
     context.font = "20px Calibri";
     context.fillText("My TEXT!", 50, 200);
 };
 imageObj.src = "mail-image.jpg"; 
};

This works fine. There is my image and the text on it. But it is still a canvas and no image. Can anybody help me?

like image 569
milan Avatar asked Sep 12 '13 16:09

milan


1 Answers

For security reasons, there's no convenient way of saving a canvas drawing to a user's local drive.

As a workaround, go "old school": Convert the canvas to an image and display it in a new window.

window.onload = function(){
 var canvas = document.getElementById("myCanvas");
 var context = canvas.getContext("2d");
 var imageObj = new Image();
 imageObj.onload = function(){
     context.drawImage(imageObj, 10, 10);
     context.font = "20px Calibri";
     context.fillText("My TEXT!", 50, 200);

     // open the image in a new browser tab
     // the user can right-click and save that image
     var win=window.open();
     win.document.write("<img src='"+canvas.toDataURL()+"'/>");    

 };
 imageObj.src = "mail-image.jpg"; 
};
like image 175
markE Avatar answered Oct 23 '22 09:10

markE