JavaScript - 以图像为中心

JavaScript - Take Center of Image

我得到一张图片,它可以是各种尺寸,但我需要取 86x86 的中心区域。此外,我还必须在 javascript 加载新图像时执行此操作,替换旧图像。

在代码的末尾,我需要用新图像更新我的 src。

function loadedImage(elem,gCount){
            var crop = { //just messing with numbers
                top : 10,
                left : 10,
                right : 20,
                bottom : 20,
            };
            var file = elem.files[0]; //I take the loaded image
            var img = document.getElementsByName('imag')[gCount]; //I take the interessed <img>

            var canvas = document.createElement("canvas"); //create canvas
            canvas.width = crop.right - crop.left; //set dimensions
            canvas.height = crop.bottom - crop.top;
            var ctx = canvas.getContext("2d"); // so we can draw
            var image = new Image(); 
            image.setAttribute('crossOrigin', 'anonymous');
            image.width = img.width;
            image.height = img.height;

            image.src = window.URL.createObjectURL(file);

            ctx.drawImage(image, -crop.left, -crop.top);
            image.src = canvas.toDataURL("image/png");
            img.src = image.src;
        }

没有显示图像

使用 load 事件侦听器等待您的图像加载。准备就绪后,您就可以开始绘图了。

要绘制图像的中心部分,源 x 坐标应为图像宽度的一半减去裁剪宽度的一半。 (源y坐标可以用类似的方法计算。)

var input = document.getElementsByName('input')[0];

input.addEventListener('change', function (e) {
  var file = e.target.files[0];
  drawCroppedImage(file, 86, 86);
});

function drawCroppedImage(file, w, h) {
  var canvas = document.getElementById('canvas');
  canvas.width = w;
  canvas.height = h;
  var ctx = canvas.getContext('2d');
  var image = new Image();
  
  image.addEventListener('load', function (e) {
    var sx = (image.width / 2) - (w / 2),  // Source X
        sy = (image.height / 2) - (h / 2), // Source Y
        dx = 0, // Destination X
        dy = 0; // Destination Y

    ctx.drawImage(image, sx, sy, w, h, dx, dy, w, h);
  });
  
  image.src = URL.createObjectURL(file);
}
<input type="file" name="input">
<br><br>
<canvas id="canvas" width="86" height="86"></canvas>