Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="app">
  <div class="pixelize">
    <h1>Pixelize!!!</h1>
    <div>
      <label>
        <input type="file" v-on:change="upload" accept="image/*" />
      </label>
    </div>
    
    <p>Original image width:{{ widthBefore }}</p>
    <p>Original image height:{{ heightBefore }}</p>
    <div>
      <h2>Before conversion preview</h2>
      <canvas id="preview-before"></canvas>
    </div>
    <div>
      <h2>変換</h2>
      <form v-on:submit.prevent="toPixel">
        <p>
          <label>  
            Number of colors(1~100)
            <input type="number" min="1" max="100" v-model="colors" />
          </label>
        </p>
        <p>
          <label>
            Width after change(1~1000)
            <input
                   type="number"
                   step="1"
                   min="1"
                   max="1000"
                   v-model="widthAfter"
                   />
          </label>
        </p>
        <p>
          <label>
            Pixel size (3 to 30)
            <input type="number" min="3" max="30" v-model="pixelSize" />
          </label>
        </p>
        <p>
          <label>
            Add grid lines
            <input type="checkbox" v-model="grid" />
          </label>
        </p>
        <p>
          <button type="submit">Pixelize!!!</button>
        </p>
      </form>
      <canvas id="preview-after"></canvas>
    </div>
  </div>
</div>
</div>
</div>
              
            
!

CSS

              
                
              
            
!

JS

              
                // Clustering
const kMeansFilter = (src, dst, width, height, colors) => {
  const vmax = 255; // Maximum value of array elements
  const loopMax = 100; //Maximum number of loops
  // Initialize
  colors = parseInt(colors);
  let centroids = Array(colors); // Keep each cluster center
  for (var c = 0; c < colors; c++) {
    var rand_i = Math.floor(Math.random() * height);
    var rand_j = Math.floor(Math.random() * width);
    centroids[c] = src.slice(
    (rand_j + rand_i * width) * 4,
    (rand_j + rand_i * width) * 4 + 3
    );
  }
  let clsts = Array(width * height); // Holds the cluster label (0 to colors-1) of each pixel
  let clstsSum = Array(colors); // For calculating the center of gravity of each cluster
  for (var c = 0; c < colors; c++) {
    clstsSum[c] = Array(3);
  }
  let clstsSize = Array(colors); //For calculating the center of gravity of each cluster
  let count = 0;
  // Main processing
  let clstsPrev = JSON.parse(JSON.stringify(clsts));
  let exitFlg = false;
  while (true) {
    for (var i = 0; i < height; i++) {
      for (var j = 0; j < width; j++) {
        var vec = src.slice((j + i * width) * 4, (j + i * width) * 4 + 3);
        var minDist = calcDistance(vec, centroids[0]);
        var minClst = 0;
        for (var c = 1; c < colors; c++) {
          var nextDist = calcDistance(vec, centroids[c]);
          if (nextDist < minDist) {
            minDist = nextDist;
            minClst = c;
          }
        }
        clsts[j + i * width] = minClst;
      }
    }
    // update centroids
    clstsSize.fill(0);
    for (var c = 0; c < colors; c++) {
      clstsSum[c].fill(0);
    }
    for (var i = 0; i < height; i++) {
      for (var j = 0; j < width; j++) {
        var clst = clsts[j + i * width];
        for (var k = 0; k < 3; k++) {
          clstsSum[clst][k] += src[(j + i * width) * 4 + k];
        }
        clstsSize[clst] = clstsSize[clst] + 1;
      }
    }
    for (var c = 0; c < colors; c++) {
      for (var k = 0; k < 3; k++) {
        centroids[c][k] =
          clstsSize[c] > 0 ? Math.floor(clstsSum[c][k] / clstsSize[c]) : 0;
      }
    }
    exitFlg =
      JSON.stringify(clsts) === JSON.stringify(clstsPrev) || count > loopMax;
    if (exitFlg) {
      break;
    }
    clstsPrev = JSON.parse(JSON.stringify(clsts));
    count++;
  }
  // Reflect clustering result
  for (var i = 0; i < height; i++) {
    for (var j = 0; j < width; j++) {
      var clst = clsts[j + i * width];
      for (var k = 0; k < 3; k++) {
        dst[(j + i * width) * 4 + k] = centroids[clst][k];
        // Maintain transparency
        dst[(j + i * width) * 4 + 3] = src[(j + i * width) * 4 + 3];
      }
    }
  }
};
// Vector distance
const calcDistance = (vec1, vec2) => {
  let dist = 0;
  for (var i = 0; i < vec1.length; i++) {
    dist += Math.pow(Math.abs(vec2[i] - vec1[i]), 2);
  }
  dist = Math.sqrt(dist);
  return dist;
};
// Make dot picture easy to see (enlarge, grid line)
const visualizePixel = (inputImageData, pixelSize, grid) => {
  const vmax = 255; // Maximum value of array elements
  const gridStep = 10; // Make grid lines thicker for each gridStep
  const newWidth = inputImageData.width * pixelSize;
  const newHeight = inputImageData.height * pixelSize;
  const outputImageData = new ImageData(
  inputImageData.width * pixelSize,
  inputImageData.height * pixelSize
  );
  // Expansion
  for (var i = 0; i < newHeight; i++) {
    for (var j = 0; j < newWidth; j++) {
      var iOld = Math.floor(i / pixelSize);
      var jOld = Math.floor(j / pixelSize);
      for (var k = 0; k < 4; k++) {
        outputImageData.data[(j + i * newWidth) * 4 + k] =
          inputImageData.data[(jOld + iOld * inputImageData.width) * 4 + k];
      }
    }
  }
  // Grid lines
  
  if (grid) {
    for (var i = 0; i < newHeight; i++) {
      for (var j = 0; j < newWidth; j++) {
        if (
        i % pixelSize == 0 ||
        j % pixelSize == 0 ||
        (i + 1) % (pixelSize * gridStep) == 0 ||
        (j + 1) % (pixelSize * gridStep) == 0
        ) {
          for (var k = 0; k < 3; k++) {
            outputImageData.data[(j + i * newWidth) * 4 + k] = vmax;
          }
          outputImageData.data[(j + i * newWidth) * 4 + k] = vmax;
        }
      }
    }
  }
  return outputImageData;
};
new Vue( {
  name: "Pixelize",
  data() {
    return {
      widthBefore: null,
      heightBefore: null,
      widthAfter: 100,
      heightAfter: null,
      colors: 3,
      pixelSize: 10,
      grid: true,
      img: null,
    };
  },
  methods: {
    upload: function(event) {
      let img = null;
      let file = event.target.files;
      if (file.length == 0) {
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(file[0]);
      // Processing when a file is read
      reader.onload = function() {
        img = new Image();
        //Processing when the image is loaded (drawing on canvas)
        img.onload = function() {
          let canvas = document.getElementById("preview-before");
          if (canvas.getContext) {
            // canvas 2d contextAssumption
            let context = canvas.getContext("2d");
            this.widthBefore = img.width;
            this.heightBefore = img.height;
            canvas.width = this.widthBefore;
            canvas.height = this.heightBefore;
            context.drawImage(img, 0, 0);
            this.img = img;
          }
        }.bind(this);
        img.src = reader.result;
      }.bind(this);
    },
    toPixel: function() {
      let canvas = document.getElementById("preview-after");
      if (canvas.getContext && this.img != null) {
        let context = canvas.getContext("2d");
        let scale = this.widthAfter / this.widthBefore;
        this.heightAfter = this.heightBefore * scale;
        canvas.width = this.widthBefore * scale;
        canvas.height = this.heightBefore * scale;
        context.scale(scale, scale);
        context.drawImage(this.img, 0, 0);
        let srcData = context.getImageData(0, 0, canvas.width, canvas.height);
        let dstData = context.createImageData(canvas.width, canvas.height);
        let src = srcData.data;
        let dst = dstData.data;
        kMeansFilter(src, dst, canvas.width, canvas.height, this.colors);
        canvas.width *= this.pixelSize;
        canvas.height *= this.pixelSize;
        let outputImageData = visualizePixel(
        dstData,
        this.pixelSize,
        this.grid
        );
        context.putImageData(outputImageData, 0, 0);
      }
    },
  },
}).$mount('#app')
              
            
!
999px

Console