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>