-->

Canvas Image Smoothing

2020-02-18 21:25发布

问题:

What is

ctx.mozImageSmoothingEnabled = false;

for webkit(or other browsers)? I need it to remove anti-aliasing because i am trying to get a pixelized effect to an image. With anti-aliasing, it looks bad-quality but with no sharp edges.

回答1:

For the <canvas> tag, WebKit nightlies after r117635 and Chrome Canary 21.0.1154.0 now have a webkitImageSmoothingEnabled attribute. (Note that this applies only to <canvas>, not to HTML elements more generally.)



回答2:

If you want to draw shape without smooth edges try to use half pixels on coordinates.

Imagine each pixel as a large square. The whole-number coordinates (0, 1, 2…) are the edges of the squares. If you draw a one-unit-wide line between whole-number coordinates, it will overlap opposite sides of the pixel square, and the resulting line will be drawn two pixels wide. To draw a line that is only one pixel wide, you need to shift the coordinates by 0.5 perpendicular to the line's direction.

For example, if you try to draw a line from (1, 0) to (1, 3), the browser will draw a line covering 0.5 screen pixels on either side of x=1. The screen can’t display half a pixel, so it expands the line to cover a total of two pixels:

But, if you try to draw a line from (1.5, 0) to (1.5, 3), the browser will draw a line covering 0.5 screen pixels on either side of x=1.5, which results in a true 1-pixel-wide line:

Source: http://diveintohtml5.info/canvas.html



回答3:

AFAIK no way yet. You might get the same effect drawing what you want pixel-by-pixel, but with more work (hey, not that much if it's something like lines).



回答4:

A quick look at the link reported by Stephan below shows the following update to this issue on the bug tracker:

The proposed value for CSS3's image-rendering 'optimize-contrast' has been implemented as '-webkit-optimize-contrast' in bug 56627. Right now in WebKit, using this will get you nearest-neighbour interpolation.

So the CSS setting -webkit-optimize-contrast looks to be the answer.



回答5:

There is a (almost one year old) bug report in webkit about this. One other possiblity would be to create your pixel art in higher resolutions and scale them down. This would probably yield better results than upsizing, but would be combined with higher traffic demands.



回答6:

Round your X and Y before showing your images on screen.

If you draw images on sub-pixels some browsers will try to anti-alias it before showing the image.

The faster way to do it is a binary OR with zero.

myObject.X = myObject.X | 0;

For a deeper explanation, take a read at this article:

http://sebleedelisle.com/2011/02/html5-canvas-sprite-optimisation/

And here is a jsperf test on rounding methods:

http://jsperf.com/math-floor-vs-math-round-vs-parseint/5