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: 400
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.

  1. <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:

  1. <section class="drop">
  2. <div class="label">
  3. <h1>DROP</h1>
  4. <h2>max 64px &times; 64px</h2>
  5. </div>
  6. <div class="content">
  7. <div class="drop-zone">
  8. <div class="drop-placeholder">
  9. DROP IMAGE HERE
  10. </div>
  11. <img class="drop-image">
  12. </div>
  13. <div class="drop-help">
  14. <div class="drop-from-desktop">
  15. Drag an image from your desktop
  16. </div>
  17. <div class="drop-from-samples">
  18. (or just click on one of these)
  19. </div>
  20. <div class="drop-samples">
  21. <img src="data:image/gif;base64,R0lGODlhEAAYALMLAJzWSjFzMQAYe4Sl1s5rOf/GjP//3sa1UlpSjHtSCBgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAAShcMmlqKozS5V6xxp1HMlhjODEkSabpMrYjbKCgPFbzgky3BuSolAgJAwfIeVTMBhbntdSQSgaS6fPRiEoCL6ElXI4JDovnFKFXA4rBvDYhVi4BAJvg96ARtwCAIFvBG4vVHWBgXhVF1JUF343F4w4fAhVbjZAFAaSRGGedZx+CmeakhedpJGnBgOprHCSfq6waKU/kLVvOH6vqRg4uGh8EhEAOw==">
  22. <img src="data:image/gif;base64,R0lGODlhEAAYALMLAP//3kohAGNjjP+9e1JKOc57Qpx7WntCKaWlcyE5YxgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASOcMlJa1VYLWy3QghBgIRGfeGIAGBiSgqgDKOauCei3Pp9Z7ASb5cYKQQCE6aA0YUyONggIMsor9NBApm07AYD5vZ3cQ12gkQhejIoDLeCnA0zAOAFwPwFgw70ZG0GB2BidBuDB3JWXgeOGC58Jy5jkScYBz+VBy9vnJkYBomcEwqfHKZAl26lg5J9rRwLEQA7">
  23. <img src="data:image/gif;base64,R0lGODlhEAAYAKIHAP+UvQApjP85c4xzjJylzv///xgYGP///yH5BAEAAAcALAAAAAAQABgAAANteLrc/jDK6Yw5F9psQF4WVmxYRVhCMYSVQRQpIX9gYd82jb34vTKGHu4EFN6INaOKZhgUAtCA7/IJCgkDgUGLSdl4BaxA4FFsseAZmbp5WW5bT9Dinr1W8nDzlBu4qWEDflZNcyAbdDMsGosLCQA7">
  24. <img src="data:image/gif;base64,R0lGODlhEAAYALMLAAAYe5zWSjFzMYSl1lpSjHtSCP//3sa1Us5rOf/GjBgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASXcMlJq1VqYTvxKV+xVYp4GKBxHFm3vm8hkvIXfq1bIDwSjp2EIZFAyEosikJIVBgxiqQEk4AiqrwcBlAEGK7O6hRL9EKdCOp3WcQM09XlGkpgwzHgYbXeI6Q1CQREVQICGAR1HX5ZdYhAU1ADCgQDAwY5GpYGkhoEBptampyTn5yQiKMKlqYKAgGFZwKOLWe1ra6GHB21EQA7">
  25. <img src="data:image/gif;base64,R0lGODlhEAAYALMLAP//3lpzvUIphMZ7Y5RaAP/OhDFKUjExMUJCQpy1pRgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASWcMkplbU0W5QSQkpWcQnQeSGlfMB3oqonm2e6rIkyDKycWqhBoYAwfUKKzlFITB6dF0vhYgRKB7qhAJDMrRSHApYpmMIUhjBWp5hyMOjAAUy4vOsVA/hQjx70Exd9QwdygIEKgwWFcxUWB3wWO1E3kHx9emiHe30WmZkVkZ4BUQakN3hxmxcVjmilBIc3BrFRtq6sIgsRADs=">
  26. <img src="data:image/gif;base64,R0lGODlhEAAYALMLAAAxMb2UAM6E/4Ra3v//3s5rOYSthJQAAP/GjClSORgYGP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAQABgAAASbcEmp6qpjqElVMkmYKIOwUUYapiA5Th7xpURrnB5ryKpyU7JCiGfDgRCymshnTCCHoNGLMkJUQlbPiVJAIACErmdaUXS/hLLlIhBovIgCqb1VuDUFecbEqZjgViZbF1YBB4cHAQpWfXFzbmaMXAdmiAdylzhiXYeOjlxZYQVpi3IwFQdxnGUcFIaIiq0wiYeGg32Wh7d9igqxHBEAOw==">
  27. </div>
  28. </div>
  29. </div>
  30. </section>
  31. <section class="scale">
  32. <div class="label">
  33. <h1>SCALE</h1>
  34. <h2>&times 10</h2>
  35. </div>
  36. <div class="content">
  37. <input class="scale-slider" type="range" min="1" max="20" step="1" value="10">
  38. <div class="scale-labels">
  39. <div class="scale-min">smaller</div>
  40. <div class="scale-max">bigger</div>
  41. </div>
  42. </div>
  43. </section>
  44. <section class="preview">
  45. <div class="label">
  46. <h1>PREVIEW</h1>
  47. <h2></h2>
  48. </div>
  49. <div class="content">
  50. <div class="preview-box">
  51. <div class="preview-anchor"></div>
  52. </div>
  53. </div>
  54. </section>
  55. <section class="css">
  56. <div class="label">
  57. <h1>CSS</h1>
  58. <h2></h2>
  59. </div>
  60. <div class="content">
  61. <textarea class="css-output" readonly></textarea>
  62. </div>
  63. </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.

  1. @import url(https://fonts.googleapis.com/css?family=Arimo:400,700);
  2.  
  3. * {
  4. box-sizing: border-box;
  5. }
  6. body {
  7. background: #eee linear-gradient(-45deg, rgba(255, 255, 255, .3) 50%, transparent 50%) 0 0 / 80px 80px;
  8. margin: 60px 20px;
  9. font-family: 'Arimo', sans-serif;
  10. color: #777;
  11. }
  12. .label {
  13. float: left;
  14. width: 290px;
  15. margin-top: -6px;
  16. text-align: right;
  17. }
  18. h1 {
  19. margin: 0;
  20. font-size: 60px;
  21. line-height: 1;
  22. color: #7e759e;
  23. }
  24. h2 {
  25. margin: 0;
  26. font-size: 30px;
  27. font-weight: normal;
  28. line-height: 1;
  29. color: #bbb;
  30. }
  31. .content {
  32. width: 620px;
  33. min-height: 130px;
  34. margin-left: 320px;
  35. padding: 0 0 40px 30px;
  36. border-left: solid 2px #ddd;
  37. text-align: left;
  38. }
  39.  
  40. .drop .content {
  41. min-height: 90px;
  42. padding-bottom: 0;
  43. }
  44. .drop-zone {
  45. position: relative;
  46. float: left;
  47. width: 110px;
  48. height: 110px;
  49. border: dashed 5px #777;
  50. border-radius: 20px;
  51. background-color: #ddd;
  52. }
  53. .drop-over {
  54. background-color: #fff;
  55. }
  56. .drop-placeholder {
  57. padding: 16px 0;
  58. vertical-align: middle;
  59. text-align: center;
  60. font-size: 20px;
  61. font-weight: bold;
  62. }
  63. .drop-image {
  64. position: absolute;
  65. top: 50%;
  66. left: 50%;
  67. display: none;
  68. }
  69. .drop-help {
  70. margin-left: 140px;
  71. text-align: center;
  72. white-space: nowrap;
  73. }
  74. .drop-from-desktop {
  75. font-size: 30px;
  76. }
  77. .drop-from-samples {
  78. font-size: 20px;
  79. color: #bbb;
  80. }
  81. .drop-samples {
  82. background-color: #ddd;
  83. border-radius: 10px;
  84. margin-top: 10px;
  85. padding: 10px 0 6px;
  86. text-align: center;
  87. }
  88. .drop-samples img {
  89. margin: 0 24px;
  90. cursor: pointer;
  91. }
  92.  
  93. .scale {
  94. display: none;
  95. }
  96. .scale-slider {
  97. width: 100%;
  98. margin: 0;
  99. }
  100. .scale-labels {
  101. font-size: 20px;
  102. }
  103. .scale-min {
  104. float: left;
  105. }
  106. .scale-max {
  107. float: right;
  108. }
  109.  
  110. .preview {
  111. display: none;
  112. }
  113. .preview-box {
  114. max-width: 100%;
  115. max-height: 480px;
  116. overflow: auto;
  117. font-size: 0;
  118. }
  119.  
  120. .css {
  121. display: none;
  122. }
  123. .css .content {
  124. min-height: 90px;
  125. padding-bottom: 0;
  126. }
  127. .css-output {
  128. width: 100%;
  129. height: 200px;
  130. border: solid 1px #ddd;
  131. }
  132.  
  133. .error {
  134. color: #9e7575;
  135. }
  136. .loaded .drop .content {
  137. min-height: 130px;
  138. padding-bottom: 40px;
  139. }
  140. .loaded .scale,
  141. .loaded .preview,
  142. .loaded .css {
  143. display: block;
  144. }

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

  1. <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.

  1. var dropImage; // global, set when image changes
  2.  
  3. $(function() {
  4. // suppress assets pop-up for codepen pro accounts
  5. $('html').on('dragenter dragover', function(e) {
  6. e.stopPropagation();
  7. });
  8. // image changed
  9. $('.drop-image').on('load', function() {
  10. if (this.naturalWidth > 64 || this.naturalHeight > 64) {
  11. showDropError('IMAGE TOO LARGE');
  12. } else {
  13. dropImage = this;
  14. calculatePixels();
  15. renderDrop();
  16. renderMarkup();
  17. }
  18. });
  19. // drag and drop stuff
  20. $('.drop-zone')
  21. .on('dragover', function() {
  22. $(this).addClass('drop-over');
  23. return false;
  24. })
  25. .on('dragleave', function() {
  26. $(this).removeClass('drop-over');
  27. return false;
  28. })
  29. .on('drop', function(e) {
  30. $(this).removeClass('drop-over');
  31. loadFromDesktop(e.originalEvent.dataTransfer.files[0]);
  32. e.preventDefault();
  33. return false;
  34. });
  35. // sample images
  36. $('.drop-samples img').on('click', function() {
  37. loadFromSamples(this.src);
  38. });
  39. $('.drop-image, .drop-samples img').on('dragstart', function(e) {
  40. // this is a band-aid to prevent confusion
  41. e.preventDefault();
  42. });
  43.  
  44. // scale slider
  45. $('.scale-slider').on('change', function() {
  46. updateScale(this.value);
  47. });
  48. });
  49.  
  50. function loadFromDesktop(file) {
  51. if (!file || file.type.indexOf('image/') !== 0) {
  52. showDropError('NOT AN IMAGE');
  53. } else {
  54. var reader = new FileReader();
  55. reader.onload = function(e) {
  56. $('.drop-image').attr('src', e.target.result);
  57. };
  58. reader.readAsDataURL(file);
  59. }
  60. }
  61.  
  62. function showDropError(message) {
  63. $('body').removeClass('loaded');
  64. $('.drop-image').hide();
  65. $('.drop-placeholder')
  66. .text(message)
  67. .addClass('error')
  68. .show();
  69. }
  70.  
  71. function loadFromSamples(src) {
  72. $('.drop-image').attr('src', src);
  73. }
  74.  
  75. function updateScale(scale) {
  76. $('.scale h2').html('&times; ' + scale);
  77. renderMarkup();
  78. }
  79.  
  80. function calculatePixels() {
  81. // create context
  82. var canvas = document.createElement('canvas');
  83. canvas.width = dropImage.naturalWidth;
  84. canvas.height = dropImage.naturalHeight;
  85. var context = canvas.getContext('2d');
  86. // draw green screen
  87. context.beginPath();
  88. context.rect(0, 0, dropImage.naturalWidth, dropImage.naturalHeight);
  89. context.fillStyle = 'rgb(1, 255, 1)';
  90. context.fill();
  91. // get image data
  92. context.drawImage(dropImage, 0, 0);
  93. var data = context.getImageData(0, 0, dropImage.naturalWidth, dropImage.naturalHeight).data;
  94. // translate image data to pixel objects
  95. var pixels = [];
  96. for (var i = 0; i < dropImage.naturalWidth * dropImage.naturalHeight; i++) {
  97. var r = data[i * 4];
  98. var g = data[i * 4 + 1];
  99. var b = data[i * 4 + 2];
  100. if(r !== 1 || g !== 255 || b !== 1) {
  101. pixels.push({
  102. x: i % dropImage.naturalWidth,
  103. y: Math.floor(i / dropImage.naturalWidth),
  104. hex: rgbToHex(r, g, b)
  105. });
  106. }
  107. }
  108. // save work
  109. dropImage.pixels = pixels;
  110. }
  111.  
  112. function renderDrop() {
  113. // show drop image centered
  114. $(dropImage)
  115. .show()
  116. .css('margin', (dropImage.naturalHeight / -2) + 'px 0 0 ' + (dropImage.naturalWidth / -2) + 'px');
  117.  
  118. // update UI
  119. $('.drop-placeholder').hide();
  120. $('.drop h2').html(dropImage.naturalWidth + 'px &times; ' + dropImage.naturalHeight + 'px');
  121. $('body').addClass('loaded');
  122. }
  123.  
  124. function renderMarkup() {
  125. var scale = parseInt($('.scale-slider').val(), 10);
  126. var marginLeft = (dropImage.naturalWidth - 1) * scale;
  127. var marginBottom = (dropImage.naturalHeight - 1) * scale;
  128.  
  129. var bgColor;
  130. var shadows = [];
  131. for (var i = 0; i < dropImage.pixels.length; i++) {
  132. var pixel = dropImage.pixels[i];
  133. if (i === 0 && pixel.x === 0 && pixel.y === 0) {
  134. // topmost leftmost pixel becomes background color
  135. bgColor = pixel.hex;
  136. }
  137. else {
  138. // add a box shadow
  139. var x = pixel.x * scale;
  140. if (x !== 0) {
  141. x += 'px';
  142. }
  143. var y = pixel.y * scale;
  144. if (y !== 0) {
  145. y += 'px';
  146. }
  147. shadows.push(x + ' ' + y + ' ' + pixel.hex);
  148. }
  149. }
  150. // create style string
  151. var style =
  152. 'display: inline-block;n' +
  153. 'width: ' + scale + 'px;n' +
  154. 'height: ' + scale + 'px;n' +
  155. 'margin: 0 ' + marginLeft + 'px ' + marginBottom + 'px 0;n' +
  156. (bgColor ? 'background-color: ' + bgColor + ';n' : '') +
  157. 'box-shadow:n ' + shadows.join(',n ') + ';';
  158. // update preview stuff
  159. $('.preview-anchor').attr('style', style);
  160. $('.preview h2').html((dropImage.naturalWidth * scale) + 'px &times; ' + (dropImage.naturalHeight * scale) + 'px');
  161.  
  162. // update css stuff
  163. $('.css-output').val(style);
  164. $('.css h2').html(style.match(/n/g).length + ' lines');
  165. }
  166.  
  167. function rgbToHex(r, g, b) {
  168. var hex = ((1 << 24) + (r << 16) + (g << 8) + b)
  169. .toString(16)
  170. .slice(1);
  171. // short format
  172. if (hex[0] === hex[1] && hex[2] === hex[3] && hex[4] === hex[5]) {
  173. hex = hex[0] + hex[2] + hex[3];
  174. }
  175. return '#' + hex;
  176. }

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