前言
随着浏覽器對的canvas的支援,業務上使用的範圍也越來越廣了。
以前前端需要下載下傳圖檔時,需要後端在
Content-Disposition: attatchment; filename="xx.png"
的http頭(nginx的配置方式可以直接 看最下面),現在用
canvas
也是可以實作的了。
下面完整的Demo在
這裡demo裡有兩個圖檔連結,分别是設定了cors頭部了和沒有設定的。讀者朋友可以自行設定看下效果,注意打開console面闆看下報錯
擷取圖檔
CORS
圖檔與站點同域的還好,由于canvas使用的場景對image的跨域有要求的,得圖檔的http response傳回
Access-Control-Allow-Origin: http://somedomain
async function getImg(src) {
let img = new Image()
img.crossOrigin = '' // allow cors, 這裡是camelCase,不是crossorigin
let [width ,height] = await new Promise(resolve => {
img.onload = function () {
// 擷取圖檔的原始尺寸
resolve([img.naturalWidth, img.naturalHeight])
}
img.src = src
})
儲存圖檔到canvas
// 儲存圖檔到canavs
let canvas = document.getElementById('canvas')
canvas.width = width // 上一步擷取的寬度
canvas.height = height
let ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
// save img
let link = document.getElementById('link')
link.href = canvas.toDataURL('image/png')
}
Nginx的配置
# ~ 為正則比對
# * 為忽略大小寫
location ~* \.(jpe?g|png|gif|webp)$ {
# 此行添加頭部
add_header Access-Control-Allow-Origin *;
root /data/images;
try_files $uri =404;
}
坑
上面是JS中動态生成的img。在html中寫好的Img标簽裡設定
crossorigin
屬性,浏覽器就會抛出
DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
的錯誤。是以避免在html裡寫對應的Img吧。
<img crossorigin='' />
canvas的其它使用
右鍵圖檔儲存
可參考下面的這篇文章:
weworkweplay.com/play/saving…打個廣告
公司現在急招前端開發,坐标深圳南山,有興趣的可以看
,直接把履歷發我郵箱吧。[email protected]
原文釋出時間為:2018年06月26日
原文作者:teal-front
本文來源:
掘金 https://juejin.im/entry/5b3a29f95188256228041f46如需轉載請聯系原作者