javascript loaded image is blurry (PNG)

耗尽温柔 提交于 2019-12-24 06:25:10

问题


I am working on a school project (only couple months of JS knowledge), and i stumbled upon this problem with drawing sprites on my canvas. To draw i use these bits of code.

treeImage = new Image();
treeImage.src = "sprites/treeSprites.png"; 

function rocks() { //to create the rock
    this.x = 1920 * Math.random(); //random location on the width of the field
    this.y = ground[Math.round(this.x/3)]; //ground is an array that stores the height of the ground
    this.draw = function() {
        ctx.save();
        ctx.translate(this.x, this.y);
        ctx.rotate(Math.tan((ground[Math.floor(this.x/3)]-ground[Math.floor(this.x/3)+1])/-3));
        //^rotating based on its position on the ground^
        ctx.drawImage(treeImage, 200, 50, 50, 50, -25, -50, 50, 50);
        ctx.restore();
    }
}

len = rockArray.length; //every frame
for (var i = 0;i<len;i++) {
    rockArray[i].draw();
}

as you can see i only request a 50 by 50 from the image, and this 50 by 50 as you can see in the image below, is drawn correctly by me (for as far as i know), but exactly outside of the 50 by 50 there are black lines, which shouldn't interfere because i only request the square within the black lines. but when i draw the rock, the black outlines are visible. (assume i cant remove the black lines for too detailed reasons)

proof that its truly a 50x50, and how it looks on my canvas

what i am guessing is that the image JavaScript stores when i load the image is made blurry, and then when i request that part from the image, the lines around are visible too, as the blur "spread" the lines into the square i request.

is this the case? is there a way i can prevent this? or maybe another way to solve this? because i know people have made pixel art games within canvas, and their images arent blurry at all so to say.


回答1:


Use canvas.imageSmoothingEnabled = false.

This will make the image sharp instead of blurry.

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled




回答2:


If you draw a vertical line at x=5 and width = 1, the canvas actually draws the line from 4.5 to 5.5 this results in aliasing and a fuzzy line. A quick way to remedy that so it is a solid line is to offset the entire canvas by half a pixel before doing anthing else.

ctx.translate(-0.5, -0.5);



来源:https://stackoverflow.com/questions/47560855/javascript-loaded-image-is-blurry-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!