javascriptjquerycsspixelate

Image with fixed width to fill div


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!


Solution

  • 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>