Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

Code helps me draw pixel art.

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

I want to create my own artwork in pixel style, but I feel like I don't have that artistic talent... So I'm thinking, can I convert a normal image into pixel style myself? 🤔

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 smoothing processing 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 cannot achieve the pixelated 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 smoothing 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('Input is not valid')
    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.