如何在 HTML 中允许跨域使用图片和画布?

htmlweb developmentfront end technology更新于 2024/12/28 7:40:17

要允许跨域使用图片和画布,服务器必须在其 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) {
            // 仅允许对托管在安全服务器上的图像进行跨域请求
            
            // (HTTPS/HTTP) server
            return;
         }  
         // 创建一个新的 Image 对象并将其 src 属性设置为图像的 url
         
         // that we want to load
         var image = new Image();
         image.src = url;
         
         // 当图像加载完成后,将 img 元素的 src 属性设置为
         
         // 图片的 url
         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>
         // 获取 id="remote-image" 的 img 元素的引用
         var remoteImage = document.getElementById('remote-image');
         
         // 将 img 元素的 src 属性设置为我们想要的图像的 url
         // to load
         remoteImage.src = 'https://i.natgeofe.com/n/2a832501-483e-422f-985c-0e93757b7d84/6_square.jpg';
         
         // 调用 allowCrossOrigin 函数,传入 img 元素和 url
         // 我们要加载的图像
         allowCrossOrigin(remoteImage, 'https://i.natgeofe.com/n/2a832501-483e-422f-985c-0e93757b7d84/6_square.jpg');
      </script>
   </body>
</html>


相关文章


有用资源