0

I have a question, I have an image which I want after some jquery event pixelizate. I dont want to use pixelate.js or other plugins, they are not good for my project.

What I want, automatically change image to a smaller "copy" of the same picture with css image-rendering: pixelated but without second copy of image. It is possible with CSS/javascript?

Sorry for my bad english and thanks!

shitwithcode
  • 367
  • 1
  • 5
  • 10

2 Answers2

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

You could set the size of the img o be the max size of it's parent. Therefore, if the parent resizes, the images should also resize accordingly.

wmash
  • 4,032
  • 3
  • 31
  • 69
  • How will that help me with to get current image pixelated? – shitwithcode Jun 21 '16 at 15:55
  • So, when the image is smaller, you want it to be pixelated? When larger, you want it to be clear? – wmash Jun 21 '16 at 15:56
  • Currently I have image which have width: 100%; and it is in parent. And after some jquery event which I have in my project I dont need to change image width, just need pixelated image. – shitwithcode Jun 21 '16 at 15:58
  • Okay so does the image want tostay 100% width of parent? Also, when the parent is smaller, do you want to pixelate image? And when parent is larger, do you want to pixelate it or not? – wmash Jun 21 '16 at 16:00
  • Parent its not important. Image should be always 100%, but I want to know, how I can make it pixelated without using scripts like pixelate.js. – shitwithcode Jun 21 '16 at 16:02
0

You can do this with HTML5's canvas element. Essentially, we want to take our image, draw it to a small canvas, and then stretch the canvas to fill the original image size. Here's an example:

$('.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>
Rose Kunkel
  • 3,102
  • 2
  • 27
  • 53