diff options
| author | jmoenig <jens@moenig.org> | 2013-04-30 11:49:26 +0200 |
|---|---|---|
| committer | jmoenig <jens@moenig.org> | 2013-04-30 11:49:26 +0200 |
| commit | 0c4779f02819d16355192e894a2fdc77bbf366e4 (patch) | |
| tree | b5a2dd123e6562584f393b972c2f2af1b1de4191 /objects.js | |
| parent | 9c9d761cc03ee8989ec92a142b36f96f09774a8d (diff) | |
| download | snap-0c4779f02819d16355192e894a2fdc77bbf366e4.tar.gz snap-0c4779f02819d16355192e894a2fdc77bbf366e4.zip | |
Costume shrink-wrapping
Diffstat (limited to 'objects.js')
| -rw-r--r-- | objects.js | 88 |
1 files changed, 87 insertions, 1 deletions
@@ -120,7 +120,7 @@ PrototypeHatBlockMorph*/ // Global stuff //////////////////////////////////////////////////////// -modules.objects = '2013-April-25'; +modules.objects = '2013-April-30'; var SpriteMorph; var StageMorph; @@ -4512,6 +4512,92 @@ Costume.prototype.bounds = function () { return new Rectangle(0, 0, this.width(), this.height()); }; +// Costume shrink-wrapping + +Costume.prototype.shrinkWrap = function () { + // adjust my contents' bounds to my visible bounding box + var bb = this.boundingBox(), + ext = bb.extent(), + pic = newCanvas(ext), + ctx = pic.getContext('2d'); + + ctx.drawImage( + this.contents, + bb.origin.x, + bb.origin.y, + ext.x, + ext.y, + 0, + 0, + ext.x, + ext.y + ); + this.rotationCenter = this.rotationCenter.add(bb.origin); + this.contents = pic; + this.version = Date.now(); +}; + +Costume.prototype.boundingBox = function () { + // answer the rectangle surrounding my contents' non-transparent pixels + var row, + col, + pic = this.contents, + w = pic.width, + h = pic.height, + ctx = pic.getContext('2d'), + dta = ctx.getImageData(0, 0, w, h); + + function getAlpha(x, y) { + return dta.data[((y * w * 4) + (x * 4)) + 3]; + } + + function getLeft() { + for (col = 0; col < w; col += 1) { + for (row = 0; row < h; row += 1) { + if (getAlpha(col, row)) { + return col; + } + } + } + return 0; + } + + function getTop() { + for (row = 0; row < h; row += 1) { + for (col = 0; col < h; col += 1) { + if (getAlpha(col, row)) { + return row; + } + } + } + return 0; + } + + function getRight() { + for (col = w - 1; col >= 0; col -= 1) { + for (row = h - 1; row > 0; row -= 1) { + if (getAlpha(col, row)) { + return col; + } + } + } + return w - 1; + } + + function getBottom() { + for (row = h - 1; row >= 0; row -= 1) { + for (col = w - 1; col >= 0; col -= 1) { + if (getAlpha(col, row)) { + return row; + } + } + } + return h - 1; + } + + return new Rectangle(getLeft(), getTop(), getRight(), getBottom()); +}; + // Costume duplication Costume.prototype.copy = function () { |
