我得到了一张图片,大小都可以,但我需要取中心面积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;
}没有显示图像。
发布于 2019-09-11 19:41:22
使用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>
https://stackoverflow.com/questions/57890972
复制相似问题