(适应于纯色图片)
1.vue文件中创建canvas
<!-- 落图图片改色 --> <canvas id="mycanvas"></canvas>
2.创建changeImgColor.js文件
let ctx = null; let canvas = null; let base64Info = null; export function setImgColor(url) { return new Promise((resolve) => { let myImage = new Image(); myImage.src = url; let width = myImage.width; let height = myImage.height; canvas = document.getElementById('mycanvas'); if (canvas.getContext) { ctx = canvas.getContext('2d'); myImage.onload = () => { // console.log('加载图片', width, height) // 图片绘制 ctx.drawImage(myImage, 0, 0); // 然后获取图片数据 var imageData = ctx.getImageData(0, 0, 34, 36); var length = imageData.data.length; var rc = randomColor(); var colorArr = rc.split(','); for (var index = 0; index < length; index += 4) { // 这里可以对 r g b 进行计算(这里的rgb是每个像素块的rgb颜色) imageData.data[index] = colorArr[0]; // r imageData.data[index + 1] = colorArr[1]; // g imageData.data[index + 2] = colorArr[2]; // b } // 更新新数据 ctx.putImageData(imageData, 0, 0); // canvas转base64 base64Info = getImageBase64Data(91, 70) // console.log('1111', base64Info) resolve(base64Info) } } else { console.log('图片未创建!') } }) } function randomColor() { // 得到随机的颜色值 var r = Math.floor(Math.random() * 256); var g = Math.floor(Math.random() * 256); var b = Math.floor(Math.random() * 256); return r + ',' + g + ',' + b; } function getImageBase64Data(w, h) { let cropImgInfo = ctx.getImageData(0, 0, w, h) let newCanvas = document.createElement('canvas') newCanvas.width = w newCanvas.height = h let newCtx = newCanvas.getContext('2d') newCtx.putImageData(cropImgInfo, 0, 0) let base64 = newCanvas.toDataURL() return base64 }
3.引入改色工具并使用
import { setImgColor } from '@/utils/changeImgColor.js'
let imgs = await setImgColor('images/remoteSence/loc2.png')
标签:Canvas,vue,imageData,canvas,myImage,let,var,Math,图片 From: https://www.cnblogs.com/wq805/p/17685764.html