繁体   English   中英

如何使用 JavaScript 裁剪图像区域?

[英]How can I crop an area of an image using JavaScript?

如何使用 JavaScript 裁剪图像区域? 正如我所读到的,我必须使用 canvas 在其上投影图像。

使用以下代码,我正在切割图像的一个区域,但切割区域的大小不是指定的。

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.onload = function() { // draw cropped image var sourceX = 0; var sourceY = 0; var sourceWidth = 500; var sourceHeight = 150; var destWidth = sourceWidth; var destHeight = sourceHeight; var destX = canvas.width / 2 - destWidth / 2; var destY = canvas.height / 2 - destHeight / 2; context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight); }; imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
 <canvas id="myCanvas" style="border:1px solid red"></canvas>

我试图在这张图片中代表我想要做的事情。

在此处输入图像描述

我的主要问题是 canvas 不适应裁剪图像的大小以及最终heightsourceHeight )和widthsourceWidth )它们不是我指定的

我该如何解决?

问题

您的源“宽度”与图像的宽度相同。

解决方案

将 ctx.drawImage 与 9 arguments 一起使用时,可以将其视为剪切和粘贴。

您想将轮廓“剪切”为红色,然后将其“粘贴”到新的居中位置。 您想一直“剪切”到源的中途点 所以你需要 select 一直到图像的中点。

我还建议可能将变量名称从“源”更改为“crop”(cropX、cropWidth 等)以更好地反映其目的,因为它不再是“源”的真正宽度。

如果您希望图像填满整个 canvas,请将其“粘贴”为画布的宽度和高度(0,0)

context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, canvas.width, canvas.height);

编码

...
var context = canvas.getContext('2d');
    var imageObj = new Image();

    imageObj.onload = function() {
        // crop from 0,0, to 250,150
        var cropX = 0;
        var cropY = 0;
        var cropWidth = 250;
        var cropHeight = 150;

        //resize our canvas to match the size of the cropped area
        canvas.style.width = cropWidth;
        canvas.style.height = cropHeight;

        //fill canvas with cropped image
        context.drawImage(imageObj, cropX, cropY, cropWidth, cropHeight, 0, 0, canvas.width, canvas.height);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
...

您需要告诉canvas您要显示的图像的大小,以确保canvas具有desiredWith的大小;

但是,您的示例图像的大小为438 × 300 ,因此很难裁剪到 500 像素。

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.src = 'https://placehold.it/700x700'; imageObj.onload = function() { const desiredWidth = 500; const desiredHeight = 150; canvas.width = desiredWidth; canvas.height = desiredHeight; context.drawImage(imageObj, 0, 0, desiredWidth, desiredHeight, 0, 0, desiredWidth, desiredHeight); console.log(canvas.width, canvas.height); };
 <canvas id="myCanvas" style="border:1px solid red"></canvas>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM