App下載

html5中怎么實(shí)現(xiàn)Canvas 跨域脫坑?實(shí)現(xiàn)案例分享!

猿友 2021-07-26 16:00:58 瀏覽數(shù) (1905)
反饋

在html5中大家是怎么解決跨域問題的呢?那么今天我們就來探討講講有關(guān)于:“html5中怎么實(shí)現(xiàn)Canvas 跨域脫坑?實(shí)現(xiàn)案例分享!”這個(gè)方面的問題,下面是小編整理的相關(guān)內(nèi)容。

這里記錄下使用 Canvas 繪圖過程中所遇到的跨域問題和解決方案。先來看下實(shí)現(xiàn)方法。

實(shí)現(xiàn)方法

目標(biāo)圖片一般是由 圖片 + 文本 構(gòu)成。無論是千奇百怪的大小圖片,還是變幻莫測(cè)的各式文本,都能用 canvas api drawImage 和 fillText 方法來完成。

基本流程如下:

1、獲取 canvas 上下文 -- ctx

const canvas = document.querySelector(selector)
const ctx = canvas.getContext('2d')

2、繪圖

忽略圖片上的內(nèi)容,直接用 drawImage 將其畫到 canvas 畫布上即可。

const image = new Image()
image.src = src
image.onload = () => {
    ctx.save()
    // 這里我們采用以下參數(shù)調(diào)用
    this.ctx.drawImage(image, dx, dy, dWidth, dHeight)
    this.ctx.restore()
}

drawImage 有3種參數(shù)使用方式,具體用法可以查看MDN 文檔。

3、獲取圖像數(shù)據(jù)

調(diào)用 HTMLCanvasElement DOM 對(duì)象提供的 toBlob(), toDataURL() 或 getImageData() 方法,即可。

canvas.toBlob(blob => {
    // 你要的 blob
}, mimeType, encoderOptions)

這里的 mimeType 默認(rèn)值為 image/png。encoderOptions 指定了圖片質(zhì)量,可用于壓縮,不過需要 mimeType 格式為 image/jpeg 或者 image/webp。

Canvas 跨域

正常情況下,如果需要將繪制好的圖像輸出,我們可以調(diào)用 canvas 的 toBlob(), toDataURL() 或 getImageData() 方法來獲取到圖像數(shù)據(jù)。然而,遇到圖片跨域的情況就有些尷尬了??赡芑貓?bào)如下錯(cuò)誤:

Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.

或者

Access to image at 'https://your.image.src' from origin 'https://your.website' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

先來看看第2種情況。

Access-Control-Allow-Origin

如果你跨域使用某些圖片資源,并且該服務(wù)未正確響應(yīng) Access-Control-Allow-Origin 頭信息, 則會(huì)報(bào)出如下錯(cuò)誤信息:

Access to image at 'https://your.image.src' from origin 'https://your.website' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

說明不允許跨域訪問,那么你可以試著讓后臺(tái)修改 Access-Control-Allow-Origin 的值為 * 或 your.website, 或者改用同域資源(考慮下?)。

接下來,我們來解決第1種情況。

img.crossOrigin = 'Anonymous'

為避免未經(jīng)許可拉取遠(yuǎn)程網(wǎng)站信息而導(dǎo)致的用戶隱私泄露(如 GPS 等信息,具體可搜索 Exif),在調(diào)用 canvas 的 toBlob(), toDataURL() 或 getImageData() 會(huì)拋出安全錯(cuò)誤:

Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.

如果你的圖片服務(wù)允許跨域使用(如果不允許,見上條),那么你該考慮下給 img 元素加上 crossOrigin 屬性,即:

const image = new Image()
image.crossOrigin = 'Anonymous'
image.src = src

如此,你便可以拿到圖片數(shù)據(jù)了。如果沒招,換同域資源吧~

以上就是有關(guān)于:“html5中怎么實(shí)現(xiàn)Canvas 跨域脫坑?實(shí)現(xiàn)案例分享!”這個(gè)問題的相關(guān)內(nèi)容,當(dāng)然更多有關(guān)于HTML5這方面的內(nèi)容我們可以在W3Cschool中進(jìn)行學(xué)習(xí)! 



0 人點(diǎn)贊