Editing Canvas Pixel Manipulation This edit will create a new revision. Your details (optional) Name Email (won’t be displayed; might be used for Gravatar) URL Test case details Title * Published (uncheck if you want to fiddle around before making the page public) Description (in case you feel further explanation is needed)(Markdown syntax is allowed) Tests two different methods of manipulating pixels using the canvas. Are you a spammer? (just answer the question) Preparation code Preparation code HTML (this will be inserted in the <body> of a valid HTML5 document in standards mode) (useful when testing DOM operations or including libraries) <canvas id="canvas" height="256" width="256"></canvas> Include JavaScript libraries as follows: <script src="//cdn.ext/library.js"></script> Define setup for all tests (variables, functions, arrays or other objects that will be used in the tests) (runs before each clocked test loop, outside of the timed code region) (e.g. define local test variables, reset global variables, clear canvas, etc.) (see FAQ) var canvas = document.getElementById('canvas'); var canvasWidth = canvas.width; var canvasHeight = canvas.height; var ctx = canvas.getContext('2d'); var imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight); var data = imageData.data; var buf = new ArrayBuffer(imageData.data.length); var buf8 = new Uint8Array(buf); var data32 = new Uint32Array(buf); var direct = new Int32Array( data.buffer ); var directUnsigned = new Uint32Array( data.buffer ); Define teardown for all tests (runs after each clocked test loop, outside of the timed code region) (see FAQ) ctx.putImageData(imageData, 0, 0); Code snippets to compare Test 1 Title Async (check if this is an asynchronous test) Code for (var y = 0; y < canvasHeight; ++y) { for (var x = 0; x < canvasWidth; ++x) { var index = (y * canvasWidth + x) * 4; var value = x * y & 0xff; data[index] = value; // red data[++index] = value; // green data[++index] = value; // blue data[++index] = 255; // alpha } } Test 2 Title Async (check if this is an asynchronous test) Code for (var y = 0; y < canvasHeight; ++y) { for (var x = 0; x < canvasWidth; ++x) { var value = x * y & 0xff; data32[y * canvasWidth + x] = (255 << 24) | // alpha (value << 16) | // blue (value << 8) | // green value; // red } } imageData.data = buf8; Test 3 Title Async (check if this is an asynchronous test) Code for (var y = 0; y < canvasHeight; ++y) { for (var x = 0; x < canvasWidth; ++x) { var value = x * y & 0xff; direct[y * canvasWidth + x] = (255 << 24) | // alpha (value << 16) | // blue (value << 8) | // green value; // red } } Test 4 Title Async (check if this is an asynchronous test) Code for (var y = 0; y < canvasHeight; ++y) { for (var x = 0; x < canvasWidth; ++x) { var value = x * y & 0xff; directUnsigned[y * canvasWidth + x] = (255 << 24) | // alpha (value << 16) | // blue (value << 8) | // green value; // red } }