toDataURL throw Uncaught Security exception

前端 未结 2 1815
时光取名叫无心
时光取名叫无心 2020-12-10 18:34

I have two Set of Code for testing html5 canvas

Set 1 - Work perfectly



        
相关标签:
2条回答
  • 2020-12-10 19:10

    This is a CORS issue - Gravatar sends the correct headers, you just need to put the correct attribute in:

    <img id="preview1" crossorigin="anonymous" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
    
    function getBase64() {
        var img = document.getElementById("preview1");
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.width;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, "")); 
    }
    getBase64();
    

    Note that your first example also failed when I tested it, just as it should.

    0 讨论(0)
  • 2020-12-10 19:20

    You can just use crossOrigin Attribute.

    var img= new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.src = url;
    
    0 讨论(0)
提交回复
热议问题