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
  • Question, where does the toDataURL() comes from ? Commented Jan 18, 2015 at 21:53
  • my bad, i meant document.getElementById('canvasImg').src = dataURL, Commented Jan 20, 2015 at 7:51

2 Answers 2

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"; }; 
Sign up to request clarification or add additional context in comments.

2 Comments

The image url needs to be changed when you look at the fiddle. There is a cross-site problem.
@BradenBrown Thnx. Fixed it with different link. Still a warning from jsfiddle itself but the image loads.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.