HTMLImageElement: crossOrigin 屬性
HTMLImageElement 介面的 crossOrigin 屬性是一個字串,用於指定檢索影像時使用的跨域資源共享 (CORS) 設定。
值
一個指定獲取影像資源時使用的 CORS 模式的關鍵字字串。如果您不指定 crossOrigin,則在不使用 CORS 的情況下獲取影像(即 no-cors 獲取模式)。
允許的值為:
anonymous-
<img>元素髮起的請求將mode設定為cors,並將credentials模式設定為same-origin。這意味著,如果影像從文件載入的同一來源獲取,則會啟用 CORS 併發送憑據。 use-credentials-
HTMLImageElement發起的請求將使用cors模式和include憑據模式;無論獲取來自哪個域,該元素的所有影像請求都將使用 CORS。
如果 crossOrigin 是一個空字串(""),則會選擇 anonymous 模式。
示例
在此示例中,將建立一個新的 <img> 元素並將其新增到文件中,以匿名狀態載入影像;該影像將使用 CORS 載入,並且將為所有跨域載入使用憑據。
JavaScript
以下程式碼演示瞭如何為 <img> 元素設定 crossOrigin 屬性,以配置新建立影像獲取的 CORS 訪問。
js
const container = document.querySelector(".container");
function loadImage(url) {
const image = new Image(200, 200);
image.addEventListener("load", () => container.prepend(image));
image.addEventListener("error", () => {
const errMsg = document.createElement("output");
errMsg.value = `Error loading image at ${url}`;
container.append(errMsg);
});
image.crossOrigin = "anonymous";
image.alt = "";
image.src = url;
}
loadImage("clock-demo-400px.png");
HTML
html
<div class="container">
<p>
Here's a paragraph. It's a very interesting paragraph. You are captivated by
this paragraph. Keep reading this paragraph. Okay, now you can stop reading
this paragraph. Thanks for reading me.
</p>
</div>
CSS
css
body {
font:
1.125rem/1.5 "Helvetica",
"Arial",
sans-serif;
}
.container {
display: flow-root;
width: 37.5em;
border: 1px solid #d2d2d2;
}
img {
float: left;
padding-right: 1.5em;
}
output {
background: rgb(100 100 100 / 100%);
font-family: "Courier New", monospace;
width: 95%;
}
結果
規範
| 規範 |
|---|
| HTML # dom-img-crossorigin |
瀏覽器相容性
載入中…