JS利用canvas将图片转为像素画
近几天迷上了像素画,沉迷像素画的世界无法自拔。画画虽好,但过程是有点费时间,突然灵光一闪💡,为何不直接用图片生成像素画,省得哼哧哼哧的画画了🤣
构思步骤
- 像素画就是把高像素的图片拿来降低像素值。
- 可以将正方形区域内的颜色统一为平均色。
- 再赋值给画布就是一个小方块了,那岂不是就是像素画了。
代码
poly
参数代表聚合的小方块的像素值
HTML
<img id="source" src="image/Lena.jpg" alt="">
<canvas id="myCanvas"></canvas>
JavaScript
window.onload = function () {
const poly = 24
const image = document.getElementById('source')
const width = image.width
const height = image.height
const canvas = document.getElementById('myCanvas');
canvas.width = width
canvas.height = height
const ctx = canvas.getContext("2d");
ctx.drawImage(image, 0,0,width,height);
//取得图像数据
const canvasData = ctx.getImageData(0, 0, width, height);
let area = {}
let count = 0
for (let x = 0; x < canvas.height; x+=poly) {
count++
for (let y = 0; y < canvas.width; y+=poly) {
area = {
w:(y+poly)>canvas.width?parseInt(canvas.width%poly):poly,
h:(count)*poly>canvas.height?parseInt(canvas.height%poly):poly
}
const idx = (y + x * canvas.width) * 4;
averageColors(idx,area)
}
}
ctx.putImageData(canvasData, 0, 0);
function averageColors(idx, area){
let aveR = aveColors(idx,area)
let aveG = aveColors(idx+1,area)
let aveB = aveColors(idx+2,area)
fullColors(idx,{aveR:aveR, aveG:aveG, aveB:aveB}, area)
}
function aveColors(idx,area) {
let total = 0
for (let i=0;i<area.h;i++){
for (let j=0;j<area.w;j++){
if (canvasData.data[idx+(j*4)+(width*i*4)]){
total += canvasData.data[idx+(j*4)+(width*i*4)]
}
}
}
return total/(area.w*area.h)
}
function fullColors(idx,rgb, area){
for (let i=0;i<area.h;i++){
for (let j=0;j<area.w;j++){
canvasData.data[idx+0+(j*4)+(width*i*4)]=rgb.aveR
canvasData.data[idx+1+(j*4)+(width*i*4)]=rgb.aveG
canvasData.data[idx+2+(j*4)+(width*i*4)]=rgb.aveB
}
}
}
}
才艺展示
这次测试选择大名鼎鼎的
Lena
女士
poly=12
poly=24
poly=48