Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript; Adding text on image using canvas and save to image

i just want to make a page where u can type a text and add it on selected image and save that as new image.

I tried to do it in few ways, but without luck.

<body>
<canvas id = "idCanvas" width = "576" height = "577"> </canvas>
<img id="canvasImg" width = "576" height = "577"></img>
<script>
window.onload = function(){
  var canvas = document.getElementById('idCanvas');
  var context = canvas.getContext('2d');
  var imageObj = new Image();
  var dataURL = canvas.toDataURL();

  imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0, 576, 577);
    context.font = "20px Calibri";
    context.fillText("My TEXT!", 50, 200);

    document.getElementById('canvasImg').src = toDataURL();
    window.alert(dataURL);
  };
  imageObj.src =  "image.png";

  };



</script>

When i use toDataURL() in img src, the image won't be displayed, it only works if i'm not using drawImage in canvas.

like image 522
Deividas Pekunas Avatar asked Oct 12 '25 02:10

Deividas Pekunas


1 Answers

Ok so yes it will not work for security reason, but there is a solution. See here a working demo: FIDDLE

draw();

function draw() {

    var canvas = document.getElementById('idCanvas');
    var context = canvas.getContext('2d');

    var imageObj = new Image();


  imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
    context.font = "40px Calibri";
    context.fillStyle = "red";
    context.fillText("My TEXT!", 50, 300);

    var canvas = document.getElementById('idCanvas');
    var dataURL = canvas.toDataURL();

    alert(dataURL);
  }
imageObj.setAttribute('crossOrigin', 'anonymous');
imageObj.src = "https://loremflickr.com/400/200";
};
like image 121
Michelangelo Avatar answered Oct 14 '25 15:10

Michelangelo