Drawing images to canvas with img.crossOrigin = “Anonymous” doesn't work

后端 未结 2 1148
南笙
南笙 2020-12-08 15:56

In a client-side standalone JS application, I\'m trying to make it so I can call toDataURL() on a canvas on which I\'ve drawn some images specified by a URL. Ie I can input

相关标签:
2条回答
  • 2020-12-08 16:31

    When the server requires authorization to access the images the value should be:

    img.crossOrigin = "Use-Credentials";
    

    Otherwise the browser will give up after receiving HTTP 401.

    0 讨论(0)
  • 2020-12-08 16:40

    You must set the CORS request before the src - just swap the lines into:

    img.crossOrigin = "Anonymous";
    img.src = document.getElementById("imgbox").value;
    

    You will also need to add an onload handler to the image as loading is asynchronous:

    img.onload = function() {
        context.drawImage(this, 40, 40);
        // call next step in your code here, f.ex: nextStep();
    };
    img.crossOrigin = "Anonymous";
    img.src = document.getElementById("imgbox").value;
    
    0 讨论(0)
提交回复
热议问题