JSFiddle - React, Tailwind, and code Playground

Web Worker, Offscreen Canvas, Image Scaling Demo (fillRect)

by skibulk

HTML

<canvas id="myCanvas" width="256" height="256"></canvas>

CSS

canvas {
  border: 1px solid black;
}

JavaScript

// http://2ality.com/2017/01/messagechannel.html

console.clear();

var myCanvas = document.getElementById("myCanvas");
var myCanvasContext = myCanvas.getContext("bitmaprenderer");

var myWorkerInstance = toWorker( myWorker);

myWorkerInstance.onmessage = function( event ){
	console.log( event.data );
  myCanvas.width = event.data.bitmap.width;
  myCanvas.height = event.data.bitmap.height;
	myCanvasContext.transferFromImageBitmap( event.data.bitmap );
  
  // Not sure how well this will work, but my idea is to sort
  // the images by bytes and hopefully get close pairings
  console.log( event.data.bytes );
}

myWorkerInstance.postMessage( "run" );

// Utils ------------

// Convert a class or function into a web worker
function toWorker(fn) {

    // Web Workers require a file URL to instantiate
    // Create a blob file / url to satisfy the web worker
    var url = URL.createObjectURL(
        new Blob([
            '(' + fn.toString() + ')();'
        ], {
            type: 'application/javascript'
        })
    );

    // Initialize the web worker and release the blob file / url from memory
    var w = new Worker(url);
    URL.revokeObjectURL(url);
    url = null;
    return w;
}

function myWorker(){
	onmessage = function( event ){
		var offscreen = new OffscreenCanvas(256, 256);
		var offscreenContext = offscreen.getContext('2d');

		offscreenContext.fillStyle = "#FF0000";
		offscreenContext.fillRect(0, 50, 256, 265);
    resample_single( offscreen, 100, 100, true );
    
    // MUST calculate before transfering to bitmap
    var bytes = offscreenContext.getImageData(0,0,100,100).data.join().length;
		var bitmap = offscreen.transferToImageBitmap();
		
		postMessage( {bitmap:bitmap, bytes:bytes}, [bitmap] );
	}
  
  // https://github.com/viliusle/Hermite-resize
  function resample_single(canvas, width, height, resize_canvas) {
      var width_source = canvas.width;
      var height_source = canvas.height;
      width = Math.round(width);
      height =...