The HTML5 Canvas has no method for explicitly setting a single pixel.
It might be possible to set a pixel using a very short line, but then antialiasing and line caps might interfere.
Another way might be to create a small ImageData
object and using:
context.putImageData(data, x, y)
to put it in place.
Can anyone describe an efficient and reliable way of doing this?
There are two best contenders:
Create a 1×1 image data, set the color, and putImageData
at the location:
var id = myContext.createImageData(1,1); // only do this once per page
var d = id.data; // only do this once per page
d[0] = r;
d[1] = g;
d[2] = b;
d[3] = a;
myContext.putImageData( id, x, y );
Use fillRect()
to draw a pixel (there should be no aliasing issues):
ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
ctx.fillRect( x, y, 1, 1 );
You can test the speed of these here: http://jsperf.com/setting-canvas-pixel/9 or here https://www.measurethat.net/Benchmarks/Show/1664/1
I recommend testing against browsers you care about for maximum speed. As of July 2017, fillRect()
is 5-6× faster on Firefox v54 and Chrome v59 (Win7x64).
Other, sillier alternatives are:
using getImageData()/putImageData()
on the entire canvas; this is about 100× slower than other options.
creating a custom image using a data url and using drawImage()
to show it:
var img = new Image;
img.src = "data:image/png;base64," + myPNGEncoder(r,g,b,a);
// Writing the PNGEncoder is left as an exercise for the reader
creating another img or canvas filled with all the pixels you want and use drawImage()
to blit just the pixel you want across. This would probably be very fast, but has the limitation that you need to pre-calculate the pixels you need.
Note that my tests do not attempt to save and restore the canvas context fillStyle
; this would slow down the fillRect()
performance. Also note that I am not starting with a clean slate or testing the exact same set of pixels for each test.