I have a canvas that takes into consideration the devicePixelRatio.
This makes text and shapes look nice on so called retina displays (text is sharp, shapes are smoother etc).
Doing this makes the image display VERY NICE i.e. a 1000x500 image is diplayed great on a 500x250 canvas. Fine.
ctx.drawImage(img, 0, 0, img.width/ratio, img.height/ratio);
However, when doing that, the rest of the rendered stuff i.e. texts and shapes looks like they're rendered double, and things that are rendered once but should later disappear (it's a game where shapes shall disappear) stay on the canvas like it's completely malfunctioning.
Doing this
ctx.drawImage(img, 0, 0, img.width, img.height)
with an image that is 500x250 makes the image somewhat blurry, like all images on the web that doesn't consider the "2x" situation, but the rest of the shapes and texts are displayed fine and the logic now works as expected.
I'm probably making a rookie mistake. Any ideas? Thanks.
EDIT Just to give more information. Using drawImage on a canvas that has the 1000x500 Width x Hight (but the css of 500x250) does not let me just use an image that has the 1000x500 dimensions and render it without dividing the height and width of that image with the devicePixelRatio. This puzzles me. Why is it that you will still need to do
ctx.drawImage(img, 0, 0, img.width/ratio, img.height/ratio)
to get it right?
EDIT 2 I know you'll sigh (if you're still reading) but this seems to actually be related to rendering PNG-images. Rendering GIF works just fine. As does JPG. PNG however has some real issues. I can't figure out what I'm doing wrong. The image gets a black border around it (if that information helps), when rendering the png, that is, and text and other stuff that is rendered looks like it has black borders as well; looks strange. Both on Chrome and Safari.
Found the answer myself.
The Problem When you display a 2x-image on a canvas that is half the size of the image (in order to give retina displays a sharp looking image), all is well as long as you do not display PNG-images with alpha transparency set to lower than opaque.
The Solution Before calling
ctx.drawImage(img, 0, 0, img.width/ratio, img.height/ratio)
call
ctx.clearRect( 0, 0, canvasWidth, canvasHeight );
This took me 2 hours to figure out with a lot of trial and error. Hopefully, it helps someone else in the same situation.