簡體   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