これに対する答えは、実際にトリミングするか、単にトリミングするかによって異なります。
真のトリミングはより複雑で、次のようなことを行う必要があります。
var ctx_src = document.getElementById("someCanvasElement").getContext('2d');
var ctx_dest = document.getElementById("clippedDestinationCanvas").getContext('2d');
var img = new Image();
img.src = "/path/to/image";
img.onload(
function()
{
ctx_src.drawImage(img,0,0);
//capture a bounding rect from the user
//draw the image to a new canvas, cropped to the bounding rect
//see: http://www.w3schools.com/tags/canvas_drawimage.asp
ctx_dest.drawImage(img,crop_x,crop_y,crop_width,crop_height,0,0);
//display the destination canvas whereever you want, ie, in jquery do:
$("#clippedDestinationCanvas").show(); // or fadeIn() or whatever
});
上記の唯一のややこしい部分はクリッピング領域のキャプチャですが、それはそれほど難しいことではありません。基本的には、マウスダウンハンドラーを追加し、デルタxとデルタyの追跡を開始し、バウンディングボックスをオーバーレイとして描画します。
最終的には次のようになります。
var dragging;
var startx, starty;
var width, height;
$("body").on("mouseup",
function()
{
if(dragging)
{
dragging=false;
$("#someCanvasElement").off("mousemove");
}
});
$("#someCanvasElement").on("mousedown",
function(evt)
{
dragging=true;
startx = evt.pageX;
starty = evt.pageY;
});
$("#someCanvasElement").on("mousemove",
function(evt)
{
width = evt.pageX-startX;
height = evt.pageY-startY;
//set the style to whatever looks good
ctx_overlay.fillRect(startx, starty, width, height);
});
実際に画像をトリミングせずにこれを行うには、クリッピング領域の境界ボックスをキャプチャするために同じマウスハンドラーを実行し、CSSを使用して画像をクリップします。
もちろん、これはすべて私の頭のてっぺんから外れているので、それに合わせて変更しますが、始めるには十分なはずです。