我有一个画布,最初的尺寸为(例如)320 x 200。
通过我无法控制或可见的过程,各种圆圈,线条和文本被添加到画布中。
添加这些东西之后,我有时会得到很多空白区域,因为(例如)只添加了一行和一个圆圈,这些项目的总宽度和高度为100 x 50。
我无法预先计算将要添加的内容的宽度和高度。
有没有办法看画布来确定内容的界限?在我的场景中可以使用的一种简单方法是找到具有非白色像素的第一行和最后一行和列。
一旦确定,我相信我可以调整大小或重绘具有适当高度和宽度的画布。
以下函数用于剪切画布(通常为透明像素)
如果你不想剪辑然后取消注释边界返回并删除之后的行,你得到的矩形的顶部,左边宽度和高度不包含像素值ignoreABGR
为白色ignoreABGR = 0xFFFFFFFF
为黑色ignoreABGR = 0xFF000000
为透明ignoreABGR = 0
function clipCanvas(ctx, ignoreABGR){
var x, y, i, left, right, top, bottom, imgDat;
const w = ctx.canvas.width;
const h = ctx.canvas.height;
const data = new Uint32Array((imgDat = ctxS.getImageData(0,0,w,h)).data.buffer);
left = w
i = right = 0;
for(y = 0; y < h; y+=1){
for(x = 0; x < w; x+=1){
if(data[i++] !== ignoreABGR){
top = top === undefined ? y : top;
bottom = y;
left = x < left ? x : left;
right = x > right ? x : right;
}
}
}
// add bounds return
// return {left,top,width : (right - left) + 1, height :(bottom - top) + 1};
ctx.canvas.width = (right - left) + 1;
ctx.canvas.height = (bottom - top) + 1;
ctx.putImageData(imgDat, -left, -top);
return ctx;
}