How to scale an imageData in HTML canvas?

前端 未结 5 1610
礼貌的吻别
礼貌的吻别 2020-12-01 05:37

I have a canvas in my webpage; I create a new Image data in this canvas then I modify some pixel through myImgData.data[] array. Now I would like to scale this image and mak

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 05:50

    I needed to do it without the interpolation that putImageData() causes, so I did it by scaling the image data into a new, resized ImageData object. I can't think of any other time I've thought that using 5 nested for loops was a good idea:

    function scaleImageData(imageData, scale) {
      var scaled = c.createImageData(imageData.width * scale, imageData.height * scale);
    
      for(var row = 0; row < imageData.height; row++) {
        for(var col = 0; col < imageData.width; col++) {
          var sourcePixel = [
            imageData.data[(row * imageData.width + col) * 4 + 0],
            imageData.data[(row * imageData.width + col) * 4 + 1],
            imageData.data[(row * imageData.width + col) * 4 + 2],
            imageData.data[(row * imageData.width + col) * 4 + 3]
          ];
          for(var y = 0; y < scale; y++) {
            var destRow = row * scale + y;
            for(var x = 0; x < scale; x++) {
              var destCol = col * scale + x;
              for(var i = 0; i < 4; i++) {
                scaled.data[(destRow * scaled.width + destCol) * 4 + i] =
                  sourcePixel[i];
              }
            }
          }
        }
      }
    
      return scaled;
    }
    

    I hope that at least one other programmer can copy and paste this into their editor while muttering, "There but for the grace of god go I."

提交回复
热议问题