Why CORS on Images with HTML Canvas?

前端 未结 2 757
醉梦人生
醉梦人生 2020-12-18 01:06

Recently, I spent a bit of time researching a solution to a rather common problem in web development- I was dealing with logos middle-aligned on a transparent background, bu

相关标签:
2条回答
  • 2020-12-18 01:23

    This protects users from having private data exposed by using images to pull information from remote web sites without permission.

    Source: MDN

    0 讨论(0)
  • 2020-12-18 01:47

    Sorry, not an answer to the question but ...

    FYI: It's not

    Either the server can set the http header access-control-allow-origin: "*", or allow a developer to set the crossDomain attribute for the image to "anonymous"/"use-credentials".

    BOTH are required.

    You need to set crossOrigin because it changes the request the browser makes to the server for the image. But even if you don't set it, and the server sends the CORS headers anyway the browser will still not let you use the image unless you had set crossOrigin.

    You can see it in this example, two images, both of which receive CORS headers from the server but the browser only lets one work.

    loadAndDrawImage("https://i.imgur.com/fRdrkI1.jpg", "");
    loadAndDrawImage("https://i.imgur.com/Vn68XJQ.jpg");
    
    function loadAndDrawImage(url, crossOrigin) {
      const img = new Image();
      img.onload = function() { 
        log("For image", crossOrigin !== undefined ? "WITH" : "without", "crossOrigin set");
        try {
          const ctx = document.createElement("canvas").getContext("2d");
          ctx.drawImage(img, 0, 0);
          ctx.getImageData(0, 0, 1, 1);
          log("canvas still clean:", name);
        } catch (e) {
          error(name, ":", e);
        }
        log(" ");
      };  
      if (crossOrigin !== undefined) {
        img.crossOrigin = crossOrigin;
      }
      img.src = url;
    }
    
    function logImpl(color, ...args) {
      const elem = document.createElement("pre");
      elem.textContent = [...args].join(" ");
      elem.style.color = color;
      document.body.appendChild(elem);
    }
    
    function log(...args) {
      logImpl("green", ...args);
    }
    
    function error(...args) {
      logImpl("red", ...args);
    }
    pre { margin: 0; }
    <div>check headers in devtools</div>

    If you check the header you'll see they both received CORS headers but only one image worked.

    0 讨论(0)
提交回复
热议问题