canvas setpixel

pixel manipulation of canvas using createImageData and putImageData

by Phil Rodgers

HTML

<body>
    <canvas id='canvas' width='128' height='128'>canvas setpixel</canvas>
</body>

CSS

canvas {
    margin: 1em;
    border: 1px solid #dddddd;
}

JavaScript

/* This code illustrates a problem with IE11 and certain versions of
   the Intel HD graphics drivers. We've seen it with Intel HD Graphics
   4600 with driver version 9.18.10.3272 and several versions of IE11,
   including 11.0.9600.17420.
   
   To demonstrate the problem, click the square on the right. The code
   constructs a bitmap with shades of blue and uses putImageData to
   put it into the canvas. On other browsers you see the bitmap, but on
   the affected systems you see a white square instead, and if you then
   call getImageData it returns an all-zero bitmap (transparent black).
   
   The problem only happens if the clearRect call is made before the
   putImageData. If you comment out the clearRect call, then the bitmap
   will also appear correctly on the affected systems.
*/

var canvas,
ctx,
width,
height;

// init canvas
canvas = $('#canvas').get(0);
ctx = canvas.getContext('2d');
width = canvas.width;
height = canvas.height;
ctx.fillStyle = '#eeeeee';
ctx.fillRect(0, 0, width, height);

// setpixel
var putImageData = function () {
    var p = ctx.createImageData(128, 128);
    console.log(p.data.length);
    for (var i = 0; i < p.data.length; i += 4) {
        p.data[i + 0] = 0;
        p.data[i + 1] = 0;
        p.data[i + 2] = i % 256;
        p.data[i + 3] = 255;
    }
    ctx.clearRect(0, 0, width, height);
    ctx.putImageData(p, 0, 0);
}

$('#canvas').on('click', putImageData);