使用JavaScript+canvas实现图片裁剪

2020-05-17 06:27:24易采站长站整理

        this.iCSize = [this.csize, this.csize, this.csize, this.csize]; // resize cubes sizes
        this.bDrag = [false, false, false, false]; // drag statuses
        this.bDragAll = false; // drag whole selection
    }
    Selection.prototype.draw = function () {
        ctx.strokeStyle = ‘#666’;
        ctx.lineWidth = 2;
        ctx.strokeRect(this.x, this.y, this.w, this.h);
        // draw part of original image
        if (this.w > 0 && this.h > 0) {
            ctx.drawImage(image, this.x, this.y, this.w, this.h, this.x, this.y, this.w, this.h);
        }
        // draw resize cubes
        ctx.fillStyle = ‘#999’;
        ctx.fillRect(this.x – this.iCSize[0], this.y – this.iCSize[0], this.iCSize[0] * 2, this.iCSize[0] * 2);
        ctx.fillRect(this.x + this.w – this.iCSize[1], this.y – this.iCSize[1], this.iCSize[1] * 2, this.iCSize[1] * 2);
        ctx.fillRect(this.x + this.w – this.iCSize[2], this.y + this.h – this.iCSize[2], this.iCSize[2] * 2, this.iCSize[2] * 2);
        ctx.fillRect(this.x – this.iCSize[3], this.y + this.h – this.iCSize[3], this.iCSize[3] * 2, this.iCSize[3] * 2);
    };
    var drawScene = function () {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // clear canvas
        // draw source image
        ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
        // and make it darker
        ctx.fillStyle = ‘rgba(0, 0, 0, 0.5)’;
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        // draw selection
        selectObj.draw();
        canvas.mousedown(canvasMouseDown);
        canvas.on(“touchstart”, canvasMouseDown);
    };
    var createSelection = function (x, y, width, height) {
        var content = $(“#imagePreview”);