2

js图片转像素画的实现方式

 6 months ago
source link: https://www.fly63.com/article/detial/12657
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

今天,我们来谈一下如何用js将图片转换成像素图。首先,让我们来看一下什么是像素图。像素图就是由一个个像素点构成的图片,也就是说像素图是图像在计算机上表示的一种方式。它由每个像素的颜色和位置所组成,因此,我们可以通过操作像素的颜色和位置来达到改变像素图的效果。

  1. 像素画就是把高像素的图片拿来降低像素值。
  2. 可以将正方形区域内的颜色统一为平均色。
  3. 再赋值给画布就是一个小方块了,那岂不是就是像素画了。

代码

html格式:

<img id="source" src="image/Lena.jpg" alt="">
<canvas id="myCanvas"></canvas>
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
}
}
}
}

poly参数代表聚合的小方块的像素值。

注意事项:

  • 需要确保图片已经正确地引入或者通过URL指定;

  • 该代码仅提供了最基本的灰度化效果,如果想要添加更多特效,可能需要深入学习Canvas api及图形处理技术

链接: https://www.fly63.com/article/detial/12657


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK