Is there a way to resize image with “nearest neighbour” resampling in HTML5?

JavascriptWeb DevelopmentFront End Scripts

Yes, it is possible. Use the following −

image-rendering: -webkit-optimize-contrast; /* webkit */
image-rendering: -moz-crisp-edges /* Firefox */

Example

You need to create the offscreen canvas, then draw an image. After that just fetch the pixels.

var a = document.createElement('canvas').getContext('2d');
a.drawImage(myImg,0,0);
var image = a.getImageData(0,0,img1.width,myImg.height).data;
for (var x=0;x<img1.width;++x){
   for (var y = 0; y < img1.height; ++y){
      var i = (y*myImg.width + x)*4;
      var r = imageimageimageimage[i ];
      var g = imageimageimage[i+1];
      var b = imageimage[i+2];
      var a = image[i+3];
      ctx2.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
      ctx2.fillRect(x*zoom,y*zoom,zoom,zoom);
   }
}
raja
Published on 06-Apr-2018 13:13:18
Advertisements