Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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="w-full p-8 mb-16 pb-24">
    <div class="mt-16 grid grid-cols-2 col-gap-8">
      <img :src="original">
      <img :src="result">
      <canvas ref="canvas" class="hidden"></canvas>
    </div>

     <template v-if="runs.length">
    <h2 class="text-xl font-bold">Stats</h2>
    <table class="mt-4 w-full border border-gray-500">
      <thead>
        <tr>
          <th class="border border-gray-500 px-4 py-2">Run No.</th>
          <th class="border border-gray-500 px-4 py-2">No. of CPUs</th>
          <th class="border border-gray-500 px-4 py-2">Total Time</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(run, idx) in runs" :key="run.timestamp">
          <td class="border border-gray-500 px-4 py-2">{{ idx + 1 }}</td>
          <td class="border border-gray-500 px-4 py-2">{{ run.concurrency }}</td>
          <td class="border border-gray-500 px-4 py-2">{{ run.elapsed }}ms</td>
        </tr>
      </tbody>
    </table>
    </template>
  </div>

  <div class="py-4 px-8 fixed bottom-0 bg-black grid grid-cols-4  items-center text-white w-full mt-8">
    <h1 class="text-2xl font-bold">CPU Demo</h1>

    <div class="flex items-center">
          <label class="block font-bold text-xl" for="cpu">Concurrency Level</label>
    <select v-model="selectedConcurrency" id="cpu" name="cpu" class="ml-8 border border-black text-black py-1 px-4">
      <option :value="concurrency">Auto Detect ({{ concurrency }})</option>
      <option v-for="n in concurrencyLevels" :key="n" :value="n">{{ n }}</option>
    </select>
    </div>


    <div class="flex items-center">
      <label class="block font-bold text-xl" for="image">Image</label>
      <input type="file" id="image" name="image" class="ml-8" @change="processFile" ref="input">
    </div>

    <button @click="processFile()" class="rounded-full bg-green-600 mx-auto px-8 py-2">Run</button>
  </div>
</div>

<script type="text/js-worker">
  self.addEventListener('message', e => {
  const data = e.data.data;
  for (var i = 0; i < data.length; i += 4) {
    data[i]     = 255 - data[i];     // red
    data[i + 1] = 255 - data[i + 1]; // green
    data[i + 2] = 255 - data[i + 2]; // blue
  }

  postMessage({ status: 'done', data })
});
</script>
              
            
!

CSS

              
                html, body {
  width: 100%;
  height: 100%;
}

table {
  @apply w-full;
}

table,
th,
td {
  @apply border border-gray-500;
}

td, th {
  @apply px-4 py-2;
}

              
            
!

JS

              
                const { ref, computed } = Vue;
const { useHardwareConcurrency } = VueAdaptiveUtils;
const { chunk: chunkArray } = _;

/*
* Creates a web worker without external scripts.
*/
const createWorker = (() => { 
  let blob;
  
  return function () {
    if (blob) {
      return new Worker(blob);
    }
    
    
    const scriptBlob = new Blob(
      Array.prototype.map.call(
        document.querySelectorAll('script[type="text\/js-worker"]'),
        function (scr) { return scr.textContent; }
      ),
      { type: 'text/javascript' }
    );
    
    blob = window.URL.createObjectURL(scriptBlob)

    // Create a new worker containing all "text/js-worker" scripts.
    return new Worker(blob);
  }
})()


Vue.createApp({
  setup() {
    const { concurrency } = useHardwareConcurrency();
    const selectedConcurrency = ref(concurrency.value);
    const original = ref('');
    const result = ref('');
    const input = ref(null);
    const canvas = ref(null);
    const runs = ref([]);
    const concurrencyLevels = computed(() => {
      return new Array(concurrency.value).fill().map((_, idx) => idx + 1).filter(i => i === 1 || i % 2 === 0)
    })
    let context = null;
    concurrency;

    function createImage(src) {
      return new Promise(resolve => {
        const img = new Image();
        img.src = src;
        img.onload = () => {
          canvas.value.width = img.naturalWidth;
          canvas.value.height = img.naturalHeight;
          resolve(img);
        };
      });
    }

    async function processFile(e) {
      const file = e ? e.target.files[0] : input.value.files[0];
      result.value = '';
      if (!file) {
        return;
      }
      
      const src = URL.createObjectURL(file);
      original.value = src;
      const img = await createImage(src);
      if (!context) {
        context = canvas.value.getContext('2d');
      }

      context.drawImage(img, 0, 0);
      const width = canvas.value.width;
      const height = canvas.value.height;
      const imageData = context.getImageData(0, 0, width, height);

      // split the amout of work on the available threads
      const chunks = chunkArray(imageData.data, imageData.data.length / selectedConcurrency.value);
      const data = { length: 0 };
      const start = performance.now();
      // spawn a service worker for each thread
      for (let i = 0; i < chunks.length; i++) {
        const worker = createWorker();
        let iterId = i;
        worker.onmessage = e => {
          data[i] = e.data.data;
          data.length++;
          
          // last item
          if (data.length === chunks.length) {
            console.log(imageData.data.length);
            context.putImageData(new ImageData(new Uint8ClampedArray(Array.from(data).flat()), width, height), 0, 0);
            runs.value.push({
              concurrency: chunks.length,
              elapsed: (performance.now() - start).toFixed(2),
              timestamp: Date.now()
            });

            result.value = canvas.value.toDataURL();
          }
        };
  
        worker.postMessage({ data: chunks[i] });
      }
    }

    return {
      processFile,
      original,
      canvas,
      runs,
      concurrency,
      selectedConcurrency,
      result,
      concurrencyLevels,
      input
    };
  }
}).mount('#app')



              
            
!
999px

Console