Advertisement
here2share

$ JS Color Interpolation

Jan 13th, 2023
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <head>
  5.   <title>Color Interpolation</title>
  6. </head>
  7. <canvas id="canvas" width="580" height="580"></canvas>
  8. <script>
  9. var canvas = document.getElementById('canvas');
  10. var ctx = canvas.getContext('2d');
  11. var imgRef = ctx.createImageData(580, 580);
  12. var img = ctx.createImageData(1160, 1160);
  13.  
  14. const rnd = 20;
  15. var zoom = 0.5;
  16.  
  17. for (var i = 0; i < imgRef.data.length; i += 4) {
  18. imgRef.data[i] = 200;
  19. imgRef.data[i + 1] = 200;
  20. imgRef.data[i + 2] = 200;
  21. imgRef.data[i + 3] = 255;
  22. }
  23.  
  24. ctx.putImageData(imgRef, 0, 0);
  25.  
  26. function interpolate() {
  27. for (var i = 0; i < 1160; i++) {
  28.   for (var j = 0; j < 1160; j++) {
  29.     // Determine the corresponding pixel in the original image
  30.     let iRef = Math.floor(i / 2);
  31.     let jRef = Math.floor(j / 2);
  32.  
  33.     // Get the color values of the corresponding pixel
  34.     let r = imgRef.data[(iRef * 580 + jRef) * 4];
  35.     let g = imgRef.data[(iRef * 580 + jRef) * 4 + 1];
  36.     let b = imgRef.data[(iRef * 580 + jRef) * 4 + 2];
  37.  
  38.     // Add random noise to color values
  39.     r += Math.floor(Math.random() * (rnd * 2 + 1)) - rnd;
  40.     g += Math.floor(Math.random() * (rnd * 2 + 1)) - rnd;
  41.     b += Math.floor(Math.random() * (rnd * 2 + 1)) - rnd;
  42.  
  43.     // Clamp color values to valid range
  44.     r = Math.min(255, Math.max(0, r));
  45.     g = Math.min(255, Math.max(0, g));
  46.     b = Math.min(255, Math.max(0, b));
  47.  
  48.     // Set the color values of the current pixel in the new image
  49.     img.data[(i * 1160 + j) * 4] = r;
  50.     img.data[(i * 1160 + j) * 4 + 1] = g;
  51.     img.data[(i * 1160 + j) * 4 + 2] = b;
  52.     img.data[(i * 1160 + j) * 4 + 3] = 255;
  53.   }
  54. }
  55. animate()
  56. }
  57.  
  58. function animate() {
  59. ctx.scale(zoom, zoom);
  60. ctx.putImageData(img, -zoom/2, -zoom/2);
  61. requestAnimationFrame(animate);
  62. // alert(zoom);
  63. if (zoom < 1) {
  64. zoom += 0.02;
  65. } else {
  66. zoom = 0.5;
  67. imgRef = ctx.getImageData(0, 0, 580, 580);
  68. interpolate();
  69. }
  70. }
  71.  
  72. interpolate();
  73.  
  74. </script>
  75. </body>
  76. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement