Click here to Skip to main content
15,446,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do I draw text on an image and then save that image? I can draw on the image. but cannot save it. I get this error when attempting to save.
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.


Any help would be great.
Thanks!

Here's my code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <input type="text" id="inp"/>
<button>Save</button>
<img src="https://i.imgur.com/C7vVKLa.png" id="image" style="border: 4px solid Black;" />
<canvas id="canvas" style="width:25%" />
<script>
	var canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');
canvas.width = $('img').width();
canvas.crossOrigin = "Anonymous";
canvas.height = $('img').height();
ctx.drawImage($('img').get(0), 0, 0);
ctx.font = "24pt Verdana";
$(document).on('input','#inp',function(){
    //redraw image
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.drawImage($('img').get(0), 0, 0);
    //refill text
    ctx.fillStyle = "black";
    ctx.fillText($(this).val(),350,115);
});
$('button').click(function(){
    let img = document.getElementById('image');
    let canvas = document.getElementById('canvas');
    let image = canvas.toDataURL("image/png");
   
    img.crossOrigin = image;
    img.src = image;
});
</script>


What I have tried:

Googling - Can draw on the image but throws
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Posted
Updated 21-Apr-22 1:30am

1 solution

You are not allowed to export changed data due to security considerations. See HTMLCanvasElement.toDataURL() - Web APIs | MDN[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900