HTML Canvas: draw image without anti-aliasing

I want to make a pixel-true display of some images on my canvas. Right now, I am fetching images via Javascript, so my images are HTMLImageElement

instantiated. I can draw them in the canvas rendering context with drawImage

. However, this does anti-aliasing on the image, which I don't want.

There appears to be a lower level named image manipulation method putImageData

working on objects ImageData

. Does this method do any anti-aliasing? If not, this is a great candidate for what I'm looking for, but I haven't found out how I can convert or shine HTMLImageElement

into a copy ImageData

.

Any advice is appreciated!

Edit: My original problem was resolved, I accidentally had a coordinate that was fractional, which forces anti-aliasing. The issue of converting to an image still persists.

+2


source to share


1 answer


The only way to convert an image to an ImageData object is to draw it on the canvas first, so you need to create a temporary canvas, draw the image on it, and get the image data from it.

function imageToImageData(image) {
     var canvas = document.createElement("canvas");
     canvas.width = image.width;
     canvas.height = image.height;
     var ctx = canvas.getContext("2d");
     ctx.drawImage(image, 0, 0);
     return ctx.getImageData(0, 0, canvas.width, canvas.height);
}

      



Note that the same origin policy prevents you from calling getImageData if you are drawing an image from a different domain to the canvas, so this will only work on images from the same domain as the document . If you need to draw images from other domains, your only option is to call drawImage

the context for your main canvas directly, making sure that there are no transformations that affect accuracy.

+1


source







All Articles