• 当前标签:rgbaster

程序开发 js网络图片通过canvas获取图片颜色

依赖于 rgbaster 包, 安装rgbaster: yarn add rgbaster import analyze from 'rgbaster' export default { mounted() { this.getBackground() }, methods: { getBackground() { const that = this function getBase64Image(img, suffix) { let canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0, img.width, img.height) const dataURL = canvas.toDataURL('image/' + suffix) // 可选其他值 image/jpeg canvas = null // 释放 return dataURL } function getColors(src, cb) { const image = new Image() const splits = src.split('.') const suffix = splits[splits.length - 1] image.setAttribute('crossOrigin', 'anonymous') // 支持跨域图片 image.src = src + '?v=' + Math.random() // 处理缓存 image.onload = function () { const base64 = getBase64Image(image, suffix) cb && cb(base64) } } getColors('https://cdn.huangliangbo.com/wp-content/uploads/2019/04/zh-2.jpg', async function (base64) { const result = await analyze(base64, { scale: 0.6 }) // also supports base64 encoded image strings that.bgColor = result[0].color }) } } } 部分内容来着:canvas图片问题浅析、JS将图片转为base64编码

2019-07-11 14:36:24 216 1 0
阅读详情
  • 1
前往