简体   繁体   中英

Why is my sprite blurred when using requestAnimationFrame to move it?

I created a basic 2D game using pure JavaScript. My problem is when the sprite stops moving it is sometimes blurred sometimes not. I use requestAnimationFrame to move the sprite and keydown/keyup events trigger moving. When keyup is triggered the sprite stops moving and the default tile is set however sometimes it is showing blurred. https://arpadvas.github.io/untitled_game_project/

Since you didn't posted an minimal code example, and that I don't want to go through the raw code you linked to, this will stay as a guess (an educated one).

Generally, this happens when you draw your sprites on floating coordinates.
Since there is no way to draw on half a pixel, the pixel being the smallest unit in canvas, to smoothen drawings, the browser will by default create antialias artifacts, turning some pixels less opaque so that your eyes think it is on half a pixel. While this usually works well with realistic photographs, it doesn't at all with pixel-art.

The solution then is either to round all your coordinates, or if you are lazy, to set the imageSmoothingEnabled property of your context.

 var img = new Image(); img.onload = draw; function draw(){ i = .316252; blurred.width = round.width = noAntiAlias.width = img.width +20; blurred.height = round.height = noAntiAlias.height = img.height +20; blurred.getContext('2d').drawImage(img, 10+i, 20+i); round.getContext('2d').drawImage(img, 10, 20); var nA = noAntiAlias.getContext('2d'); nA.mozImageSmoothingEnabled = nA.msImageSmoothingEnabled = nA.webkitImageSmoothingEnabled = nA.imageSmoothingEnabled = false; noAntiAlias.getContext('2d').drawImage(img, 10+i, 20+i); }; img.src = "https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png"; 
 <canvas id="blurred"></canvas> <canvas id="round"></canvas> <canvas id="noAntiAlias"></canvas> 

Ps : this made me realize that somehow my FF doesn't smooth this particular image I used... If someone can confirm in comments, I'd be glad to dig into this further if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM