填充固定宽度的图像 div

Image with fixed width to fill div

我有一个问题,我有一张图像,需要经过一些 jquery 事件像素化处理。 我不想使用 pixelate.js 或其他插件,它们对我的项目不利。

我想要的是,自动将图像更改为具有 css 图像渲染的同一图片的较小 "copy":像素化但没有图像的第二个副本。有可能 CSS/javascript?

抱歉我的英语不好,谢谢!

img {
    height: 100%;
    width: 100%;
}

您可以将 img 的大小设置为其父项的最大大小。因此,如果父级调整大小,图像也应相应地调整大小。

您可以使用 HTML5 的 canvas 元素执行此操作。本质上,我们想要获取我们的图像,将其绘制到一个小 canvas,然后拉伸 canvas 以填充原始图像大小。这是一个例子:

$('.image-container').each(function() {
  var canvas = $(this).children('canvas').get(0),
      ctx = canvas.getContext('2d'),
      image = $(this).children('img').get(0),
      imageWidth = $(image).width(),
      imageHeight = $(image).height(),
      scaleFactor = 0.05;
  
  canvas.width = scaleFactor * imageWidth;
  canvas.height = scaleFactor * imageHeight;
  ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

  $(canvas).width(imageWidth);
  $(canvas).height(imageWidth);
});

$('#toggle-pixelization').on('click', function() {
  $('.image-container').children().toggleClass('hidden')
});
.hidden {
  display: none;
}

.image-container canvas {
  image-rendering: -moz-crisp-edges;
  image-rendering:   -o-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -ms-interpolation-mode: nearest-neighbor;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="image-container">
  <img src="https://placekitten.com/150/150" />
  <canvas class="hidden"></canvas>
</div>
<button id="toggle-pixelization">Toggle Pixelization</button>