Picture with predetermined size to occupy entire container

Seeking assistance! I am looking to pixelate an image after a jQuery event without using plugins like pixelate.js as they are not suitable for my project.

Is it possible, through CSS or JavaScript, to automatically change the image to a smaller version with the same pixelated effect achieved by setting image-rendering: pixelated?

Apologies for any language mistakes and thank you in advance!

Answer №1

If you're looking to achieve this effect using HTML5's canvas element, it involves taking an image and drawing it onto a small canvas before stretching the canvas to fit the original image size. Check out the code snippet below for a demonstration:

$('.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>

Answer №2

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

To ensure that the image always maintains the maximum size of its parent element, you can set the dimensions of the img to be equal to the parent's dimensions. This way, as the parent element resizes, the image will resize proportionally.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery event listener for clicking on elements with the class "dropdown-menu li a" is not functioning properly

I've been attempting to implement a dropdown menu using Bootstrap that displays the selected option when a user clicks on it. However, I'm encountering issues as the breakpoints set within $(document).on("click", ".dropdown-menu li ...

What is the best way to upload a file to a server while working with Vue.js in the Filemanager plugin, or how can I access a global function

How can I upload a file to the server using Vue.js in the Filemanager plugin? I have tried multiple methods and the console log shows that the upload was successful, but I am not able to see any files on the server. Does anyone know what could be wrong? & ...

The overflow:hidden feature is ineffective in Firefox, yet functions properly in both IE and Chrome browsers

I'm in the process of creating a webshop and facing an issue with my sidebar due to varying product counts on different pages. For now, I have implemented the following workaround: padding-bottom: 5000px; margin-bottom: -5000px; overflow: ...

Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the com ...

Retrieve data from json files

After retrieving this object from my controller, I have a name, a list of beans, and a list of operations: { "name": "Charge", "beans": [ ], "operations": [ { "name": "getSize", "returnType": "java.lang.Integer", "descriptio ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

Transform your Email Template with Inline Styling to mimic a Bootstrap grid, ranging from col-md-6 to col-12 styling

Currently, I am looking to create an email template. Typically, I create my email templates with each content/row separated. However, this time I need to design an email template with a layout that consists of 2 columns on desktop and switches to 1 column ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Exploring methods for testing an HTML page that utilizes jQuery for DOM manipulations

Recently, I was tasked with creating an HTML page that utilized jQuery DOM manipulations. For instance, upon clicking the submit button, a success or error message should be displayed. Testing these functionalities is something I'm familiar with in An ...

How can I send parameters to an HTML file using Node.js?

In my current code res.sendfile('./home.html',{user:req.user}), I need to figure out a way to access the user parameter directly in the HTML file without relying on a template engine. Can anyone suggest how this can be achieved? ...

place an image next to a div element

Currently, I have a table-like structure with two columns that I am struggling to make mobile responsive. Take a look at the code snippet below: setTimeout(function() { odometer.innerHTML = '1925' }) .fiftyFiftySection { back ...

Executing processes individually within AngularJS

Just making sure I understand correctly, I have a simple web service resource query function set up like this //Get country lists $scope.getCountry = function(){ $http({ method : 'GET', url : cdnLinks('country&apos ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

Is there a way to only load an external script once during a specific event on a webpage that uses all ajax?

I'm working with a basic webpage where all the links are ajax-loaded. Is there a way to load an external script only once when a link is clicked, to ensure optimal performance? ...

"Learn how to easily send media files stored on your local server via WhatsApp using Twilio with Node.js and Express

Whenever I attempt to send the PDF file created through WhatsApp, an error pops up preventing me from viewing it. easyinvoice.createInvoice(data, function(result) { //The response will contain a base64 encoded PDF file ...

Customizable jQuery fieldset toggling for dynamic form display

Looking to add a feature to fieldsets where their contents can be shown or hidden by clicking on their labels. Here's the current HTML structure: <fieldset> <legend>Fieldset 1</legend> <!-- Some input, p, div, etc. --> ...

What is the best way to insert a tagline above a form?

I'm struggling to figure out where to place a tagline above my form. I want it to be neat and clean, but haven't been successful in finding the right spot. I attempted to insert an <h2> inside the form, but it doesn't look good at al ...

Access a three.js scene from a canvas element within the local environment to make alterations

Is it necessary to keep Three.js variables (scene, camera, renderer etc.) globally? I have devised a function that initializes canvas elements by taking a DOM position and other information to build the scene. This function is then passed to a render func ...

Unable to construct Vue application after integrating webpack extension

Currently facing an issue with adding a webpack extension to build my Vue app. Despite having Vue/cli which includes webpack, I have also attempted to install different versions of webpack without success. Anyone experienced the same problem and found a so ...

What is the process for retrieving the value of the 2nd td by clicking on the checkbox in the 1st td with JavaScript

When I click on "in", I am looking to retrieve the value of "out". This can be easily understood by referring to the image below: The timesheet displayed is generated using an array. All the data is stored in the array and needs to be presented in a table ...