Skip to content

Instantly share code, notes, and snippets.

@avidrucker
Created June 6, 2024 00:53
Show Gist options
  • Save avidrucker/925df9b385082960f33c6736c11e30d6 to your computer and use it in GitHub Desktop.
Save avidrucker/925df9b385082960f33c6736c11e30d6 to your computer and use it in GitHub Desktop.
a test in pixelating an image using HTML Canvas
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pixelated Image</title>
<style>
html, body {
background-color: black;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: black;
}
.pixelated-image {
width: 500px; /* Final displayed width */
height: 500px; /* Final displayed height */
image-rendering: pixelated; /* Ensures pixelation */
image-rendering: crisp-edges; /* For better pixelation in some browsers */
}
</style>
</head>
<body>
<div class="container">
<canvas id="pixelatedCanvas" class="pixelated-image" width="28" height="28"></canvas>
</div>
<script>
const img = new Image();
img.src = 'https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg';
img.onload = () => {
const canvas = document.getElementById('pixelatedCanvas');
const context = canvas.getContext('2d');
const scale = 10; // Scale factor for pixelation
// Set canvas size to the original image size
canvas.width = img.width / scale;
canvas.height = img.height / scale;
// Draw the image scaled down
context.drawImage(img, 0, 0, canvas.width, canvas.height);
// Scale the canvas back up
const pixelatedDataURL = canvas.toDataURL();
const pixelatedImg = new Image();
pixelatedImg.src = pixelatedDataURL;
pixelatedImg.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
context.imageSmoothingEnabled = false; // Disable smoothing to keep pixelation effect
context.drawImage(pixelatedImg, 0, 0, canvas.width, canvas.height);
};
};
</script>
</body>
</html>
@avidrucker
Copy link
Author

In it's current implementation, the script needs to be re-run to test directly in the browser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment