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

如何使用JavaScript裁剪图像的某个区域?,javascript,Javascript,如何使用JavaScript裁剪图像的某个区域?正如我所读到的,我必须使用画布在上面投影图像 使用下面的代码,我正在剪切图像的一个区域,但剪切区域的大小不是指定的大小 var canvas=document.getElementById('myCanvas'); var context=canvas.getContext('2d'); var imageObj=新图像(); imageObj.onload=函数(){ //绘制裁剪图像 var-sourceX=0; var-sourceY=0;

如何使用JavaScript裁剪图像的某个区域?正如我所读到的,我必须使用画布在上面投影图像

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

var canvas=document.getElementById('myCanvas');
var context=canvas.getContext('2d');
var imageObj=新图像();
imageObj.onload=函数(){
//绘制裁剪图像
var-sourceX=0;
var-sourceY=0;
var sourceWidth=500;
var-sourceHeight=150;
var destWidth=sourceWidth;
var destHeight=源高度;
var destX=canvas.width/2-destWidth/2;
var destY=canvas.height/2-destHeight/2;
drawImage(imageObj、sourceX、sourceY、sourceWidth、sourceHeight、destX、destY、destWidth、destHeight);
};
imageObj.src=http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

您需要告诉
画布
您试图显示的图像的大小,以确保
画布
具有所需的
大小

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

var canvas=document.getElementById('myCanvas');
var context=canvas.getContext('2d');
var imageObj=新图像();
imageObj.src=https://placehold.it/700x700';
imageObj.onload=函数(){
const desiredWidth=500;
const desired height=150;
canvas.width=所需宽度;
canvas.height=所需高度;
drawImage(imageObj,0,0,desiredWidth,desiredHeight,0,0,desiredWidth,desiredHeight);
console.log(canvas.width、canvas.height);
};
问题 您的源“宽度”与图像的宽度相同

解决方案 当使用带有9个参数的ctx.drawImage时,请将其视为剪切粘贴

您想“剪切”红色轮廓,然后“粘贴”到新的居中位置。 您希望一直“剪切”到源的中间点。因此,您需要一直选择图像的中间点

我还建议将变量名从“source”改为“crop”(cropX、cropWidth等),以更好地反映其用途,因为它实际上不再是“source”的宽度

如果希望图像填充整个画布,“粘贴”画布的宽度和高度为(0,0)

代码
谢谢但是生成的画布的大小不是500px的宽度…请参见我的编辑@yavg,画布不是所需大小的原因可以通过设置像素来确定。我的意图只是灰度占据裁剪图像的100%
width 500px
and`height 150px`您希望裁剪后的图像填充画布吗?画布两侧有一个空间,根据您的回答,我希望画布的大小与裁剪后的图像一样。嗯,我对您需要的内容感到非常困惑。你不能调整画布的大小吗?或者这就是你需要帮助的地方?
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';
...