【问题标题】:javascript loaded image is blurry (PNG)javascript加载的图像模糊(PNG)
【发布时间】:2018-05-13 15:19:28
【问题描述】:

我在学校项目的画布上绘制精灵时遇到问题。我的代码:

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();
}

我只从图像中请求 50×50px。正好在 50×50 之外有黑线(不应该干扰,因为我只要求黑线内的正方形)但是当我画岩石时,黑色轮廓是可见的。 (由于其他原因,我无法删除黑线。)

我猜当我加载图像时 JavaScript 存储的图像变得模糊,然后当我从图像中请求该部分时,周围的线条也是可见的,因为模糊将线条“扩散”到我的正方形中请求。

有什么办法可以防止这种情况发生吗?

【问题讨论】:

  • 好像是防锯齿的。
  • 您使用的是高 dpi 显示器(如 4k 或视网膜)吗?另外,尝试调整 yohr 坐标。
  • @Kaiido 1920*1080,这也是我画布的大小,由于 Ceres 的回答,我现在正在四舍五入所有坐标

标签: javascript image image-processing canvas drawimage


【解决方案1】:

使用ctx.imageSmoothingEnabled = false

这将使图像清晰而不是平滑(模糊)。

(documentation)

【讨论】:

  • 这确实使它看起来更好,它对我有进一步的帮助,但黑色轮廓仍然显示link
【解决方案2】:

如果您在 x=5 和宽度 = 1 处绘制一条垂直线,画布实际上会绘制从 4.5 到 5.5 的线,这会导致锯齿和模糊线。解决此问题的一种快速方法是在执行其他操作之前将整个画布偏移半个像素。

ctx.translate(-0.5, -0.5);

(documentation)

【讨论】:

  • 这确实进一步增加了外观,当我移除旋转时,像素现在尽可能清晰,但是当岩石旋转时,问题仍然存在(岩石周围的黑线)
  • 路径描边是这样,但其他绘图方法则不然。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-24
  • 2011-10-22
  • 1970-01-01
相关资源
最近更新 更多