Johu

JS利用canvas将图片转为像素画

近几天迷上了像素画,沉迷像素画的世界无法自拔。画画虽好,但过程是有点费时间,突然灵光一闪💡,为何不直接用图片生成像素画,省得哼哧哼哧的画画了🤣

构思步骤

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

代码

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

参考

segmentfault

posted @ 2021-07-28 15:41  Johu  阅读(1705)  评论(0编辑  收藏  举报