裁剪画布图像源的确切中心

时间:2016-09-30 14:35:08

标签: javascript html css html5 canvas

我已经创建了一个输入表单,用于将上传的文件接收到canvas元素中。由于不同的图像具有不同的大小,因此上传的图像始终会拉伸以适合我的画布大小400 * 350

如何将上传图像的确切中心裁剪为我的画布大小的比例,以便将上传的图像调整到画布中。

<input type='file' id="fileUpload" />
<canvas id="up_canvas" width="400" height="350" style="border: 1px solid red;"></canvas>

<script>
//get input as canvas
function el(id){return document.getElementById(id);}

var canvas_one  = el("up_canvas");
var context_one = canvas_one.getContext("2d");

function readImage() {
if ( this.files && this.files[0] ) {
    var FR= new FileReader();
    FR.onload = function(e) {
       var img = new Image();
       img.onload = function() {
         context_one.drawImage(img, 0, 0, 400, 350);
       };
       img.src = e.target.result;
    };       
    FR.readAsDataURL( this.files[0] );
}
}

el("fileUpload").addEventListener("change", readImage, false);
</script>

1 个答案:

答案 0 :(得分:4)

要绘制图像的特定部分,您必须在drawImage()函数中提供其他参数。如果你用9个参数调用它,它是void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);,其中s代表源,你指定要绘制的图像的哪个部分。

我们总是裁剪尺寸为400x350的矩形,但我们必须计算sxsy属性。在您的情况下,您想要像这样绘制图像:

context_one.drawImage(img, 
                      (img.width - 400) / 2,   // sx, 200 pixels to the left from center
                      (img.height - 350) / 2,  // sy, 175 pixels above center
                      400, 350, 0, 0, 400, 350);  // sw, sh, dx, dy, dw, dh

如果您也提供较小的图像,则sx和sy参数将为负数。你可以像这样处理这个案子:

context_one.drawImage(img, 
                      Math.max(0, (img.width - 400) / 2),
                      Math.max(0, (img.height - 350) / 2), 
                      400, 350, 0, 0, 400, 350);  // sw, sh, dx, dy, dw, dh