range iteration

iterate once over one canvas

by dirtyd77

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
<canvas id="canvas" width="500" height="400">This text is displayed if your browser does not support HTML5 Canvas.</canvas>

<canvas id="canvas2" width="500" height="400">This text is displayed if your browser does not support HTML5 Canvas.</canvas>

CSS

canvas {
    border: 1px solid;
}

Babel + JSX

const WIDTH = 500;
const HEIGHT = 400;
const RANGE_SIZE = 2000;
let count = 0;
let count2 = 0;

let range = new Immutable.Range(0, RANGE_SIZE, 1).toJS();

let base_canvas = document.getElementById('canvas');
let base_ctx = base_canvas.getContext('2d');

let base_canvas2 = document.getElementById('canvas2');
let base_ctx2 = base_canvas2.getContext('2d');

let outputData = [
	generatePoints(),
  generatePoints(),
  generatePoints(),
  generatePoints()
];

let outputs = [
	{
  	type: 'line',
  	color: '#0000ff',
    lineWidth: 4,
    lineDash: [] 
  },
  
  {
  	type: 'line',
  	color: '#ff0000',
    lineWidth: 3,
    lineDash: [] 
  },
  {
  	type: 'line',
  	color: '#008000',
    lineWidth: 1,
    lineDash: [] 
  },
  {
    type: 'line',
  	color: '#0000ff',
    lineWidth: 1,
    lineDash: [] 
  }
];

let contexts = outputs.map(({color, lineWidth, lineDash}, i) => {
  let canvas = document.createElement('canvas');
  canvas.width = WIDTH;
  canvas.height = HEIGHT;
  var ctx = canvas.getContext('2d');
  ctx.strokeStyle = color;
  ctx.lineWidth = lineWidth;
  return ctx;
});


console.time('multicanvas');
render();
console.timeEnd('multicanvas');

console.time('default');
render2();
console.timeEnd('default');

console.log(count, count2);

function render () {
	range.forEach((r) => {
  	outputs.forEach((output, i) => {
    	let pt = outputData[i][r];
    	let ctx = contexts[i];
    	if (r === 0) ctx.moveTo(pt[0], pt[1]);
    	drawLine(ctx, pt);
      count++;
    });
  });
  
  contexts.forEach((ctx, i) => {
  	ctx.stroke();
    base_ctx.drawImage(ctx.canvas, 0, 0, WIDTH, HEIGHT, 0, 0, WIDTH, HEIGHT);
    count++;
  });
}

function render2 () {
	outputs.forEach(({color, type, lineWidth, lineDash}, i) => {
        
    let draw = type === 'line' ? drawLine : drawHash;

    base_ctx2.strokeStyle = color;
    base_ctx2.lineWidth = lineWidth;
    base_ctx2.setLineDash(lineDash);
    
    base_ctx2.beginPath();

    range.forEach((ptI) => {
    	let pt =...