Drag and Drop Pixel Art Generator

Drag and Drop Pixel Art Generator
Code Snippet:Drag and Drop Pixel Art Generator
Author: Will Boyd
Published: January 29, 2024
Last Updated: February 3, 2024
Downloads: 165
License: MIT
Edit Code online: CodeHim
Read More

This code snippet helps you to create drag and drop pixel art generator tool on your website. It transforms your images into pixelated artwork, and you can customize the scale with a live preview. It’s a user-friendly tool for turning any image into cool pixel art without any fuss.

How to Create Drag And Drop Pixel Art Generator

1. First of all, load the Prefixfree JS by adding the following CDN link into the head tag of your HTML document.

<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

2. Create an HTML structure with a container div for the pixel art generator. Example:

<section class="drop">
  <div class="label">
    <h1>DROP</h1>
    <h2>max 64px &times; 64px</h2>
  </div>
  <div class="content">
    <div class="drop-zone">
      <div class="drop-placeholder">
        DROP IMAGE HERE
      </div>
      <img class="drop-image">
    </div>
    <div class="drop-help">
      <div class="drop-from-desktop">
        Drag an image from your desktop
      </div>
      <div class="drop-from-samples">
        (or just click on one of these)
      </div>
      <div class="drop-samples">
        <img src="data:image/gif;base64,R0lGODlhEAAYALMLAJzWSjFzMQAYe4Sl1s5rOf/GjP//3sa1UlpSjHtSCBgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAAShcMmlqKozS5V6xxp1HMlhjODEkSabpMrYjbKCgPFbzgky3BuSolAgJAwfIeVTMBhbntdSQSgaS6fPRiEoCL6ElXI4JDovnFKFXA4rBvDYhVi4BAJvg96ARtwCAIFvBG4vVHWBgXhVF1JUF343F4w4fAhVbjZAFAaSRGGedZx+CmeakhedpJGnBgOprHCSfq6waKU/kLVvOH6vqRg4uGh8EhEAOw==">
        <img src="data:image/gif;base64,R0lGODlhEAAYALMLAP//3kohAGNjjP+9e1JKOc57Qpx7WntCKaWlcyE5YxgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASOcMlJa1VYLWy3QghBgIRGfeGIAGBiSgqgDKOauCei3Pp9Z7ASb5cYKQQCE6aA0YUyONggIMsor9NBApm07AYD5vZ3cQ12gkQhejIoDLeCnA0zAOAFwPwFgw70ZG0GB2BidBuDB3JWXgeOGC58Jy5jkScYBz+VBy9vnJkYBomcEwqfHKZAl26lg5J9rRwLEQA7">
        <img src="data:image/gif;base64,R0lGODlhEAAYAKIHAP+UvQApjP85c4xzjJylzv///xgYGP///yH5BAEAAAcALAAAAAAQABgAAANteLrc/jDK6Yw5F9psQF4WVmxYRVhCMYSVQRQpIX9gYd82jb34vTKGHu4EFN6INaOKZhgUAtCA7/IJCgkDgUGLSdl4BaxA4FFsseAZmbp5WW5bT9Dinr1W8nDzlBu4qWEDflZNcyAbdDMsGosLCQA7">
        <img src="data:image/gif;base64,R0lGODlhEAAYALMLAAAYe5zWSjFzMYSl1lpSjHtSCP//3sa1Us5rOf/GjBgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASXcMlJq1VqYTvxKV+xVYp4GKBxHFm3vm8hkvIXfq1bIDwSjp2EIZFAyEosikJIVBgxiqQEk4AiqrwcBlAEGK7O6hRL9EKdCOp3WcQM09XlGkpgwzHgYbXeI6Q1CQREVQICGAR1HX5ZdYhAU1ADCgQDAwY5GpYGkhoEBptampyTn5yQiKMKlqYKAgGFZwKOLWe1ra6GHB21EQA7">
        <img src="data:image/gif;base64,R0lGODlhEAAYALMLAP//3lpzvUIphMZ7Y5RaAP/OhDFKUjExMUJCQpy1pRgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASWcMkplbU0W5QSQkpWcQnQeSGlfMB3oqonm2e6rIkyDKycWqhBoYAwfUKKzlFITB6dF0vhYgRKB7qhAJDMrRSHApYpmMIUhjBWp5hyMOjAAUy4vOsVA/hQjx70Exd9QwdygIEKgwWFcxUWB3wWO1E3kHx9emiHe30WmZkVkZ4BUQakN3hxmxcVjmilBIc3BrFRtq6sIgsRADs=">
        <img src="data:image/gif;base64,R0lGODlhEAAYALMLAAAxMb2UAM6E/4Ra3v//3s5rOYSthJQAAP/GjClSORgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASbcEmp6qpjqElVMkmYKIOwUUYapiA5Th7xpURrnB5ryKpyU7JCiGfDgRCymshnTCCHoNGLMkJUQlbPiVJAIACErmdaUXS/hLLlIhBovIgCqb1VuDUFecbEqZjgViZbF1YBB4cHAQpWfXFzbmaMXAdmiAdylzhiXYeOjlxZYQVpi3IwFQdxnGUcFIaIiq0wiYeGg32Wh7d9igqxHBEAOw==">
      </div>
    </div>
  </div>
</section>
<section class="scale">
  <div class="label">
    <h1>SCALE</h1>
    <h2>&times 10</h2>
  </div>
  <div class="content">
    <input class="scale-slider" type="range" min="1" max="20" step="1" value="10">
    <div class="scale-labels">
      <div class="scale-min">smaller</div>
      <div class="scale-max">bigger</div>
    </div>
  </div>
</section>
<section class="preview">
  <div class="label">
    <h1>PREVIEW</h1>
    <h2></h2>
  </div>
  <div class="content">
    <div class="preview-box">
      <div class="preview-anchor"></div>
    </div>
  </div>
</section>
<section class="css">
  <div class="label">
    <h1>CSS</h1>
    <h2></h2>
  </div>
  <div class="content">
    <textarea class="css-output" readonly></textarea>
  </div>
</section>

3. Style the tool interface using the following CSS styles. Feel free to customize the UI elements to match your website or app’s design. Adjust the colors, sizes, or layouts as needed.

@import url(https://fonts.googleapis.com/css?family=Arimo:400,700);

* {
  box-sizing: border-box;
}
body {
  background: #eee linear-gradient(-45deg, rgba(255, 255, 255, .3) 50%, transparent 50%) 0 0 / 80px 80px;
  margin: 60px 20px;
  font-family: 'Arimo', sans-serif;
  color: #777;
}
.label {
  float: left;
  width: 290px;
  margin-top: -6px;
  text-align: right;
}
h1 {
  margin: 0;
  font-size: 60px;
  line-height: 1;
  color: #7e759e;
}
h2 {
  margin: 0;
  font-size: 30px;
  font-weight: normal;
  line-height: 1;
  color: #bbb;
}
.content {
  width: 620px;
  min-height: 130px;
  margin-left: 320px;
  padding: 0 0 40px 30px;
  border-left: solid 2px #ddd;
  text-align: left;
}

.drop .content {
  min-height: 90px;
  padding-bottom: 0;
}
.drop-zone {
  position: relative;
  float: left;
  width: 110px;
  height: 110px;
  border: dashed 5px #777;
  border-radius: 20px;
  background-color: #ddd;
}
.drop-over {
  background-color: #fff;
}
.drop-placeholder {
  padding: 16px 0;
  vertical-align: middle;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}
.drop-image {
  position: absolute;
  top: 50%;
  left: 50%;
  display: none;
}
.drop-help {
  margin-left: 140px;
  text-align: center;
  white-space: nowrap;
}
.drop-from-desktop {
  font-size: 30px;
}
.drop-from-samples {
  font-size: 20px;
  color: #bbb;
}
.drop-samples {
  background-color: #ddd;
  border-radius: 10px;
  margin-top: 10px;
  padding: 10px 0 6px;
  text-align: center;
}
.drop-samples img {
  margin: 0 24px;
  cursor: pointer;
}

.scale {
  display: none;
}
.scale-slider {
  width: 100%;
  margin: 0;
}
.scale-labels {
  font-size: 20px;
}
.scale-min {
  float: left;
}
.scale-max {
  float: right;
}

.preview {
  display: none;
}
.preview-box {
  max-width: 100%;
  max-height: 480px;
  overflow: auto;
  font-size: 0;
}

.css {
  display: none;
}
.css .content {
  min-height: 90px;
  padding-bottom: 0;
}
.css-output {
  width: 100%;
  height: 200px;
  border: solid 1px #ddd;
}

.error {
  color: #9e7575;
}
.loaded .drop .content {
  min-height: 130px;
  padding-bottom: 40px;
}
.loaded .scale,
.loaded .preview,
.loaded .css {
  display: block;
}

4. Now, load the jQuery by adding the CDN link following scripts before closing the body tag:

<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

5. Finally, ensure the JavaScript file is correctly linked, and the following code is added to initialize the pixel art generator.

var dropImage; // global, set when image changes

$(function() {
  // suppress assets pop-up for codepen pro accounts
  $('html').on('dragenter dragover', function(e) {
    e.stopPropagation();
  });
  
  // image changed
  $('.drop-image').on('load', function() {
    if (this.naturalWidth > 64 || this.naturalHeight > 64) {
      showDropError('IMAGE TOO LARGE');
    } else {
      dropImage = this;
      calculatePixels();
      renderDrop();
      renderMarkup();
    }
  });
  
  // drag and drop stuff
  $('.drop-zone')
    .on('dragover', function() {
      $(this).addClass('drop-over');
      return false;
    })
    .on('dragleave', function() {
      $(this).removeClass('drop-over');
      return false;
    })
    .on('drop', function(e) {
      $(this).removeClass('drop-over');
      loadFromDesktop(e.originalEvent.dataTransfer.files[0]);
      e.preventDefault();
      return false;
    });
  
  // sample images
  $('.drop-samples img').on('click', function() {
    loadFromSamples(this.src);
  });
  
  $('.drop-image, .drop-samples img').on('dragstart', function(e) {
    // this is a band-aid to prevent confusion
    e.preventDefault();
  });

  // scale slider
  $('.scale-slider').on('change', function() {
    updateScale(this.value);
  });
});

function loadFromDesktop(file) {
  if (!file || file.type.indexOf('image/') !== 0) {
    showDropError('NOT AN IMAGE');
  } else {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('.drop-image').attr('src', e.target.result);
    };
    reader.readAsDataURL(file);
  }
}

function showDropError(message) {
  $('body').removeClass('loaded');
  $('.drop-image').hide();
  $('.drop-placeholder')
    .text(message)
    .addClass('error')
    .show();
}

function loadFromSamples(src) {
  $('.drop-image').attr('src', src);
}

function updateScale(scale) {
  $('.scale h2').html('&times; ' + scale);
  renderMarkup();
}

function calculatePixels() {
  // create context
  var canvas = document.createElement('canvas');
  canvas.width = dropImage.naturalWidth;
  canvas.height = dropImage.naturalHeight;
  var context = canvas.getContext('2d');
  
  // draw green screen
  context.beginPath();
  context.rect(0, 0, dropImage.naturalWidth, dropImage.naturalHeight);
  context.fillStyle = 'rgb(1, 255, 1)';
  context.fill();
  
  // get image data
  context.drawImage(dropImage, 0, 0);
  var data = context.getImageData(0, 0, dropImage.naturalWidth, dropImage.naturalHeight).data;
  
  // translate image data to pixel objects
  var pixels = [];
  for (var i = 0; i < dropImage.naturalWidth * dropImage.naturalHeight; i++) {
    var r = data[i * 4];
    var g = data[i * 4 + 1];
    var b = data[i * 4 + 2];
    
    if(r !== 1 || g !== 255 || b !== 1) {
      pixels.push({
        x: i % dropImage.naturalWidth,
        y: Math.floor(i / dropImage.naturalWidth),
        hex: rgbToHex(r, g, b)
      });
    }
  }
  
  // save work
  dropImage.pixels = pixels;
}

function renderDrop() {
  // show drop image centered
  $(dropImage)
    .show()
    .css('margin', (dropImage.naturalHeight / -2) + 'px 0 0 ' + (dropImage.naturalWidth / -2) + 'px');

  // update UI
  $('.drop-placeholder').hide();
  $('.drop h2').html(dropImage.naturalWidth + 'px &times; ' + dropImage.naturalHeight + 'px');
  $('body').addClass('loaded');
}

function renderMarkup() {
  var scale = parseInt($('.scale-slider').val(), 10);
  var marginLeft = (dropImage.naturalWidth - 1) * scale;
  var marginBottom = (dropImage.naturalHeight - 1) * scale;

  var bgColor;
  var shadows = [];
  for (var i = 0; i < dropImage.pixels.length; i++) {
    var pixel = dropImage.pixels[i];
    
    if (i === 0 && pixel.x === 0 && pixel.y === 0) {
      // topmost leftmost pixel becomes background color
      bgColor = pixel.hex;
    }
    else {
      // add a box shadow
      var x = pixel.x * scale;
      if (x !== 0) {
        x += 'px';
      }
      var y = pixel.y * scale;
      if (y !== 0) {
        y += 'px';
      }
      shadows.push(x + ' ' + y + ' ' + pixel.hex);
    }
  }
  
  // create style string
  var style =
    'display: inline-block;n' +
    'width: ' + scale + 'px;n' +
    'height: ' + scale + 'px;n' +
    'margin: 0 ' + marginLeft + 'px ' + marginBottom + 'px 0;n' +
    (bgColor ? 'background-color: ' + bgColor + ';n' : '') +
    'box-shadow:n  ' + shadows.join(',n  ') + ';';
  
  // update preview stuff
  $('.preview-anchor').attr('style', style);
  $('.preview h2').html((dropImage.naturalWidth * scale) + 'px &times; ' + (dropImage.naturalHeight * scale) + 'px');

  // update css stuff
  $('.css-output').val(style);
  $('.css h2').html(style.match(/n/g).length + ' lines');
}

function rgbToHex(r, g, b) {
  var hex = ((1 << 24) + (r << 16) + (g << 8) + b)
    .toString(16)
    .slice(1);
  
  // short format
  if (hex[0] === hex[1] && hex[2] === hex[3] && hex[4] === hex[5]) {
    hex = hex[0] + hex[2] + hex[3];
  }
  
  return '#' + hex;
}

Run your website or app locally to test the integration. Drag and drop an image onto the designated area, adjust the scale, and preview the pixel art. Debug any issues that may arise during testing.

That’s all! hopefully, you have successfully created the Pixel Art Generator tool on your website/app. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X