Skip to content

Instantly share code, notes, and snippets.

@mubaidr
Forked from timdown/trim_canvas.js
Created October 3, 2020 16:28
Show Gist options
  • Save mubaidr/65b48dbba11f080e37df8a6830b7b80d to your computer and use it in GitHub Desktop.
Save mubaidr/65b48dbba11f080e37df8a6830b7b80d to your computer and use it in GitHub Desktop.

Revisions

  1. @timdown timdown created this gist Jul 26, 2017.
    36 changes: 36 additions & 0 deletions trim_canvas.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    var trimCanvas = (function() {
    function rowBlank(imageData, width, y) {
    for (var x = 0; x < width; ++x) {
    if (imageData.data[y * width * 4 + x * 4 + 3] !== 0) return false;
    }
    return true;
    }

    function columnBlank(imageData, width, x, top, bottom) {
    for (var y = top; y < bottom; ++y) {
    if (imageData.data[y * width * 4 + x * 4 + 3] !== 0) return false;
    }
    return true;
    }

    return function(canvas) {
    var ctx = canvas.getContext("2d");
    var width = canvas.width;
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var top = 0, bottom = imageData.height, left = 0, right = imageData.width;

    while (top < bottom && rowBlank(imageData, width, top)) ++top;
    while (bottom - 1 > top && rowBlank(imageData, width, bottom - 1)) --bottom;
    while (left < right && columnBlank(imageData, width, left, top, bottom)) ++left;
    while (right - 1 > left && columnBlank(imageData, width, right - 1, top, bottom)) --right;

    var trimmed = ctx.getImageData(left, top, right - left, bottom - top);
    var copy = canvas.ownerDocument.createElement("canvas");
    var copyCtx = copy.getContext("2d");
    copy.width = trimmed.width;
    copy.height = trimmed.height;
    copyCtx.putImageData(trimmed, 0, 0);

    return copy;
    };
    })();