4

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.

2 Answers2

3

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";
};
Michelangelo
  • 5,888
  • 5
  • 31
  • 50
0

First of all, Should it be canvas.toDataURL() ?

Here is a similar example with getting contents into image element http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/

Also I was getting the following error when image is loaded from another hostname:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

When image is not added to canvas it works fine, so issue could be related to CORS HTTP headers not added with image. Try removing

context.drawImage(imageObj, 0, 0, 576, 577); 

to see that it works without image

Here is a demo based on code in question. http://jsbin.com/logikuwefo/1/edit

Community
  • 1
  • 1
Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55