如何在 HTML 中允許跨域使用影像和畫布?


要允許跨域使用影像和畫布,伺服器必須在其 HTTP 響應中包含適當的 CORS(跨域資源共享)標頭。可以將這些標頭設定為允許特定來源或方法,或允許任何來源訪問該資源。

HTML 畫布

HTML5 畫布是網頁上由 JavaScript 程式碼控制的矩形區域。可以在畫布上繪製任何內容,包括影像、形狀、文字和動畫。該畫布是建立遊戲、圖形和 Web 應用程式的絕佳工具。

方法

允許跨域使用影像和畫布的方法是將以下內容新增到標頭中 -

Access-Control-Allow-Origin - *

這將允許跨域使用所有影像和畫布元素。

示例

以下是允許跨域使用影像和畫布的完整示例。要執行它,只需在 Web 瀏覽器中開啟 HTML 檔案。

<!DOCTYPE html>
<html>
<head>
   <script>
      function allowCrossOrigin(img, url) {
         if (url.indexOf('https://') !== 0 && url.indexOf('http://') !== 0) {
            // only allow cross-origin requests for images that are hosted on a secure
            
            // (HTTPS/HTTP) server
            return;
         }  
         // create a new Image object and set its src property to the url of the image
         
         // that we want to load
         var image = new Image();
         image.src = url;
         
         // when the image has loaded, set the src property of the img element to the
         
         // url of the image
         image.onload = function() {
            img.src = url;
         };
      }
   </script>
</head>
   <body>
      <!-- define an img element and set its src property to a local image -->
      <img id='local-image' src='https://cdn.pixabay.com/photo/2012/08/27/14/19/mountains-55067__340.png' width='200' height='200'>
      <!-- define another img element and try to set its src property to
      an image that is hosted on a different domain -->
      <img id='remote-image' width='200' height='200'>
      <script>
         // get a reference to the img element with id="remote-image"
         var remoteImage = document.getElementById('remote-image');
         
         // set the src property of the img element to the url of the image that we want
         // to load
         remoteImage.src = 'https://i.natgeofe.com/n/2a832501-483e-422f-985c-0e93757b7d84/6_square.jpg';
         
         // call the allowCrossOrigin function, passing in the img element and the url
         // of the image that we want to load
         allowCrossOrigin(remoteImage, 'https://i.natgeofe.com/n/2a832501-483e-422f-985c-0e93757b7d84/6_square.jpg');
      </script>
   </body>
</html>

更新於:2023 年 2 月 13 日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.