html5-canvas 使用画布裁剪图像

示例

本示例显示了一个简单的图像裁剪功能,该功能获取图像和裁剪坐标并返回裁剪后的图像。

function cropImage(image, croppingCoords) {
    var cc = croppingCoords;
    var workCan = document.createElement("canvas"); // 创建一个画布
   workCan.width= Math.floor(cc.width);  // 将画布分辨率设置为裁剪的图像尺寸
   workCan.height= Math.floor(cc.height);
    var ctx = workCan.getContext("2d");    // 获取2D渲染界面
    ctx.drawImage(image, -Math.floor(cc.x), -Math.floor(cc.y)); // 绘制图像偏移以将其正确放置在裁剪区域上
   image.src= workCan.toDataURL();       // 将图像源设置为画布作为数据URL
    return image;
}

使用

var image = new Image();
image.src = "image URL"; // 加载图像
image.onload = function () {  // 加载时
    cropImage(
        this, {
        x :this.width/ 4,     // 作物保持中心
        y :this.height/ 4,
        width :this.width/ 2,
        height :this.height/ 2,
    });
    document.body.appendChild(this);  // 将图像添加到DOM
};