LOADING...

Preview

Pen ID
Unlock Campus Themeforest adv

 

Code


    

Lab: Pixel Art Maker

Choose Grid Size

Pick A Color

Design Canvas

Left click to paint - Shift click to erase - Drag possible

CSS
body {
    text-align: center;
}

h1 {
    font-family: 'Press Start 2P', cursive;
    font-size: 50px;
    margin: 0.8em;
}

h2 {
    margin: 1em 0 0.25em;
}

h2:first-of-type {
    margin-top: 0.5em;
}

table,
tr,
td {
    border: 1px solid black;
}

table {
    border-collapse: collapse;
    margin: 0 auto;
}

tr {
    height: 20px;
}

td {
    width: 20px;
}

p {
    font-size: 16px;
    padding: 2px;
    margin: 2px 2px 15px 2px;
}

button{
    margin-top: 15px;
}

input[type=number] {
    width: 6em;
}
JS
$(document).ready(function() {
  // Create a grid upon user's submiting the grid size, color in the "pixels" with color picked through color picker

  // Variables
  const canvas = $('#pixel_canvas');
  let leftMouse; // For the dragging functionality

  // Functions
  function makeGrid() {
    // Table and size variables	
    const height = Number($('#input_height').val());
    const width = Number($('#input_width').val());
    // Delete table contents
    canvas.empty();
    // Create table rows and cells
    for (let i = 1; i <= height; i++) {
      canvas.append('');
      let j = 1;
      while (j <= width) {
        $('tr').last().append('');
        j++;
      }
    }
  }

  // Make grid event
  $('#btn').click(function(e) {
    e.preventDefault();
    makeGrid();
  });

  // Click color + shift click erase
  canvas.on('click', 'td', function(e) {
    if (e.shiftKey) {
      $(this).css('background-color', ''); // Remove inline styling on right-clicked td
    } else {
      const color = $('#colorPicker').val();
      $(this).css('background-color', color); // Change the background-color of affected element to the colorPicker value
    }
  });
  // Drag color + shift drag erase
  canvas.mousedown(function() {
    leftMouse = true;
  })
  canvas.mouseup(function() {
    leftMouse = false;
  })
  canvas.on('mousemove', 'td', function(e) {
    if (e.shiftKey && leftMouse) {
      $(this).css('background-color', ''); // Remove inline styling on right-clicked td
    } else if (leftMouse) {
      const color = $('#colorPicker').val();
      $(this).css('background-color', color); // Change the background-color of affected element to the colorPicker value
    }
  });

  // Erase all button
  $('button').click(function(e) {
    e.preventDefault();
    $('td').css('background-color', '');
  })

  // Context menu off on grid
  canvas.on('contextmenu', 'td', function() {
    return false; // Don't show context menu
  });
});
Wed, 12/27/2017 - 07:02

Related Codes

Pen ID
Pen ID
Pen ID
Square Adv