画布上的图像模糊

时间:2020-03-26 18:44:38

标签: javascript html css canvas html5-canvas

在画布上绘制图像会使图像非常模糊。但是随着图像放大,图像变得清晰。我无法解决问题。

我正在使用的图片:https://images.unsplash.com/photo-1512819432727-dbcb57a06f13?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80

codepen链接:https://codepen.io/AdnanHashmi/pen/eYNQPoX

即使放大页面,也显示在画布上绘制的图像是模糊的和走私的。

这是它的外观。 Helo此处的左图是在画布上绘制的图像,而右图则是使用标签在屏幕上绘制的。

我的代码:

const canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var dpi = window.devicePixelRatio;
var img = new Image();
img.src =
  "https://images.unsplash.com/photo-1512819432727-dbcb57a06f13?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80";
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.style.width = canvas.width.toString() + "px";
canvas.style.height = canvas.height.toString() + "px";

img.onload = () => {
  var newWidth = canvas.width * dpi;
  var newHeight = canvas.height * dpi;

  canvas.style.width = newWidth.toString() + "px";
  canvas.style.height = newHeight.toString() + "px";

  ctx.drawImage(img, 100, 100, 100, 150);
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

canvas {
  image-rendering: pixelated;
}

img[src$=".gif"],
img[src$=".png"] {
  image-rendering: -moz-crisp-edges; /* Firefox */
  image-rendering: -o-crisp-edges; /* Opera */
  image-rendering: -webkit-optimize-contrast; /* Webkit (non-standard naming) */
  image-rendering: crisp-edges;
  -ms-interpolation-mode: nearest-neighbor; /* IE (non-standard property) */
}

.sharp {
  position: absolute;
  top: 100px;
  left: 250px;
  width: 100px;
  height: 150px;
}
<canvas></canvas>
<img src="https://images.unsplash.com/photo-1512819432727-dbcb57a06f13?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80" class="sharp" alt="" srcset="">

0 个答案:

没有答案