10

How can I disable the antialias effect in the following code ? I'm using Chrome 29.

JSFiddle here

var canvas = document.getElementById( 'test' );
var context = canvas.getContext( '2d' );

// These lines don't change anything
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;

context.beginPath();
context.arc(100, 100, 100, 0, Math.PI * 2, true );
context.closePath();

context.fillStyle = 'red';
context.fill( );
Maël Nison
  • 7,055
  • 7
  • 46
  • 77
  • this question makes me think of this one, which i answered : http://stackoverflow.com/questions/14424648/nice-ellipse-on-a-canvas/14429346#14429346 In a few words : with a quite big performance hit, you can post-process the draw or re-implement the primitives without antialiasing (quite some work maybe), but there's no way to get it done as fast without antialiasing. – GameAlchemist Aug 31 '13 at 23:08
  • When I was making a graphing script, I found if you draw same thing 20 times, the anti-aliased pixels stack up to become aliased. The faster way is to draw the desired shapes on an image buffer, clamp the alpha (0% or 100%) by reading the data, and draw the image buffer into the canvas. (I don't have time to write the code) – Ming-Tang Sep 01 '13 at 07:08
  • Please also see my "retro canvas" project here: https://github.com/epistemex/retro-context-canvas (it's free) –  Nov 19 '14 at 06:01
  • That link is now https://github.com/epistemex/8-bit (and there's also this one: https://github.com/mohayonao/gretro) – 1j01 Nov 02 '16 at 21:42

2 Answers2

6

The imageSmoothingEnabledonly affects images drawn to canvas using drawImage() (hence the name imageSmoothingEnabled). There is sadly no way to disable this for lines and shapes.

As with 6502's answer and previous answers on SO you will need to implement "low-level" methods to achieve this.

Here are some links to some common algorithms for various primitives:

The way you need to implement this is to get the x and y coordinates from these formulas. Then you need to either to use rect(x, y, 1, 1) or set a pixel directly by altering the image data buffer directly. The latter tend to be faster for these sort of things.

In both cases you will have a relatively huge performance reduction as you need to iterate using JavaScript versus browser's internal compiled iteration.

Community
  • 1
  • 1
  • Re "reduction", What about OpenGL? Is the performance still penalized? – Pacerier Nov 04 '17 at 21:47
  • @Pacerier OpenGL is not relevant here.. did you mean WebGL? You could implement a solution in WebGL using shader. –  Nov 05 '17 at 12:51
1

Unfortunately there is no portable way to disable antialiasing when drawing on a canvas.

The only solution I found is reimplementing graphic primitives writing directly on the image data.

6502
  • 112,025
  • 15
  • 165
  • 265