Calculate bounding box of arbitrary pixel-based drawing

后端 未结 3 569
萌比男神i
萌比男神i 2020-12-19 08:05

Given a contiguous drawing of arbitrary pixels (e.g. on an HTML5 Canvas) is there any algorithm for finding the axis-aligned bounding box that is more efficient than simply

3条回答
  •  攒了一身酷
    2020-12-19 08:34

    I dislike the current answer. Here's my code that I plugged into OP website. It's much faster in firefox and chrome.

    The idea is check all pixels on x axis to see if there's a hit on the Y axis. If so update Y and increase X so we can scan for max X

    function contextBoundingBox(ctx,alphaThreshold){
        if (alphaThreshold===undefined) alphaThreshold = 15;
        var w=ctx.canvas.width,h=ctx.canvas.height;
        var data = ctx.getImageData(0,0,w,h).data;
    
        let minX=w;
        let maxX=0
        let minY=h
        let maxY=0
        for(let y=0; y

提交回复
热议问题