您可以使用drawImage()方法的剪切参数并将剪切的图像绘制到动态创建的画布上。
一个例子可以是:
function getClippedRegion(image, x, y, width, height) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
// source region dest. region
ctx.drawImage(image, x, y, width, height, 0, 0, width, height);
return canvas;
}
这将返回一个画布元素,其中已经绘制了剪切的图像。您现在可以直接使用画布将其绘制到另一个画布上。
使用示例;在你的主代码中你可以这样做:
var canvas = document.getElementById('myScreenCanvas'),
ctx = canvas.getContext('2d'),
image = document.getElementById('myImageId'),
clip = getClippedRegion(image, 50, 20, 100, 100);
// draw the clipped image onto the on-screen canvas
ctx.drawImage(clip, canvas.width * Math.random(), canvas.height * Math.random());