0

Hi I want to convert img to data url. ex ) test.jpg -> data:image/jpg;base64/sdfeffsjfsakjf....fefsadf

But I is not work.

Error code is

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at HTMLImageElement.img.onload

And I search this message. people say, add "img.setAttribute('crossOrigin', 'anonymous');" But is not work.

Can you check this code?

<html>
<head>

</head>

<script src="jquery-1.12.3.js"></script>
<script>
$(document).ready(function(){
    console.log('good');
    console.log($('#tt'));
var myCanvas = document.getElementById('nn');
var ctx = myCanvas.getContext('2d');
var img = document.getElementById('tt');
//var img = new Image();
//img.setAttribute('crossOrigin', 'anonymous');
img.crossOrigin="anonymous";
//img.src = "test.jpg";
console.log(img);
img.onload = function(){
    myCanvas.width = img.width;
    myCanvas.height = img.height;

    ctx.drawImage(img, 0, 0);

    console.log(myCanvas.toDataURL('image/jpeg'));
};
});
</script>

<body>
    <img id="tt" src="test.jpg" >
    <canvas id="nn"  width="240" height="297" style="border:1px solid #d3d3d3;"></canvas>
    <div id="gg"></div>
</body>

</html>
이경언
  • 156
  • 1
  • 11
  • 1
    searching for `Tainted canvases may not be exported` - results in MANY results on stack overflow alone - like https://stackoverflow.com/questions/22710627/tainted-canvases-may-not-be-exported – Jaromanda X Jul 14 '17 at 01:42
  • Are you trying to convert a local image file to `data URI`? Or is `"test.jpg"` a remote image file? – guest271314 Jul 14 '17 at 01:43
  • Check here.. This would let you load the image in a `` and invoke `toDataUrl()` method. [How to convert image into base64 string using javascript](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript) – bpunzalan Jul 14 '17 at 01:47
  • Note: The code presented works, as is, without the error reported in the question – Jaromanda X Jul 14 '17 at 01:49
  • @ guest271314 I try to test.jpg convert to data URL. – 이경언 Jul 16 '17 at 12:26
  • @Jaromanda X I was searh. most post doesn't work. and this code is not work. too.(((( And I search this message. people say, add "img.setAttribute('crossOrigin', 'anonymous');" But is not work.)))) – 이경언 Jul 16 '17 at 12:28
  • in fact, setting crossorigin to anonymous if the image is same origin may be the problem – Jaromanda X Jul 16 '17 at 22:52

0 Answers0