前言
canvas
可以将图片链接转 base64。入下图所示:
您也可以点击这里 图片链接转base64
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片链接转base64</title>
</head>
<body>
<script>
const convertimg2base64 = (img) => {
const canvasEl = document.createElement('canvas')
canvasEl.width = img.width
canvasEl.height = img.height
const ctx = canvasEl.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
const imgsuffix = img.src.match(/\.[^\\.]+$/)[0].substring(1).toLowerCase()
return canvasEl.toDataURL(`image/${imgsuffix}`)
}
const link = 'https://harmsworth.github.io/study-demo/static/file/cat.jpg'
const img = new Image()
img.src = link
img.crossOrigin = 'anonymous'
img.addEventListener('load', () => {
const base64 = convertimg2base64(img)
const newimg = new Image()
newimg.src = base64
document.body.appendChild(newimg)
})
</script>
</body>
</html>
在 convertimg2base64
函数中,先设置 canvas
宽高,然后才创建 canvas
上下文,具体原因,我已经在上一篇博客中具体阐述了,canvas改变宽高后发生了什么?。
这样写更优。如果先创建上下文,再改变宽高,则上下文必定会被重置成默认值,也就是说上下文会经历 2 次变化。如果先改变宽高,再创建上下文,此时,canvas
的属性已经定好了,则上下文只会变化一次。故后者更优。
总结
- 先定义
canvas
宽高,再创建canvas
上下文的写法更优