Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

Code helps me draw pixel art.

I have recently become obsessed with pixel art style, which has a retro feel to it. Since I used to play Pokémon in pixel art style when I was a child, it brings back a lot of nostalgia.
I even changed my computer wallpaper to a pixel art style. It feels great 😝

desktop.png

I wanted to create my own pixel art, but I feel like I don't have that artistic talent... So I was thinking, can I convert a normal image into pixel art? 🤔

Idea⭐#

  1. Use canvas to shrink the image, causing it to lose some pixel information.
  2. Then draw the shrunken image.
  3. Enlarge the shrunken image to reveal its pixels.

Basically, it's about enlarging a small image, which gives a blurry effect.

Code💻#

Disabling the browser's smooth processing actually means disabling anti-aliasing.
Using regular expressions to limit the input box to only accept numbers from 0 to 100, which represents the percentage of image scaling (100 means no scaling, which doesn't achieve the pixelation effect).

const pixel =  (canvas, image, scale)=> {
    scale *= 0.01;
    
    canvas.width = image.width;
    canvas.height = image.height;

    // Shrink the image
    let scaledW = canvas.width * scale;
    let scaledH = canvas.height * scale;

    let ctx = canvas.getContext('2d');
  
    // Disable the browser's smooth processing
    ctx.imageSmoothingEnabled = false;
    ctx.mozImageSmoothingEnabled = false;
    ctx.webkitImageSmoothingEnabled = false;
    ctx.msImageSmoothingEnabled = false;

    // Draw the shrunken image
    ctx.drawImage(image, 0, 0, scaledW, scaledH);
    // Restore the shrunken image to its original size
    ctx.drawImage(canvas, 0, 0, scaledW, scaledH, 0, 0, canvas.width, canvas.height);
  };


btn.addEventListener('click', function(){
  const Regex = new RegExp(/^100$|^(\d|[1-9]\d)(\.\d+)*$/)
  let scale = input.value;
  if(scale==''){
    scale = 40;
  }
  if(!Regex.test(scale)){
    window.alert('Invalid input')
    return;
  }
  console.log(scale);
  pixel(canvas,img,scale);
}, false);

Result👇#

eg.png

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.