AmazingCounters.com

[canvas入坑3] 类似ps中魔术棒或者画图中油漆桶的功能

查看效果请到 http://philippica.github.io/  点击fill

 

这功能其实实现很low,最早高一看黑书的时候看到了floodfill算法感觉好神奇,转念一想这不就是bfs么!!被高大上名词骗了有木有

 

所以先设置一个阈值var threshold;它的含义和photoshop魔术棒中容差的含义相同,当它等于0时表现出来的功能就是画图的油漆桶

 

然后进行bfs,从鼠标按下的点开始做

 

唔,js里面shift unshift pop push这四个Array上的函数天然的让queue和stack这两种数据结构实现了啊有木有,只是不知道这些函数实现的时间复杂度

 

很low的代码:

    var dx = new Array(0, 0, -1, 1, -1, -1, 1, 1);
    var dy = new Array(1, -1, 0, 0, -1, 1, -1, 1);
    var threshold = 0;
    $('#range').attr("value", 0);
    $('#range').unbind();
    $('#range').change(function()
    {
        threshold = parseInt($('#range').val()) * 4;
    });


    $('#myCanvas').unbind();
    $('#myCanvas').click(function(e)
    {
        var ppImgData = context.getImageData(0, 0, ppCanvasWidth, ppCanvasHeight);
        var mouseX = e.pageX - this.offsetLeft;
        var mouseY = e.pageY - this.offsetTop;
        var fillR = 0;
        var fillG = 255;
        var fillB = 255;
        var R = ppImgData.data[(mouseY * ppCanvasWidth + mouseX) * 4];
        var G = ppImgData.data[(mouseY * ppCanvasWidth + mouseX) * 4 + 1];
        var B = ppImgData.data[(mouseY * ppCanvasWidth + mouseX) * 4 + 2];
        var ppQueue = new Array();
        var ppVisit = new Array();
        var ppField = dx.length;
        ppQueue.push(new ppPoint(mouseX, mouseY));
        while(ppQueue.length != 0)
        {
            var u = ppQueue.shift();
            for(var i = 0; i < ppField; i++)
            {
                var X = u.x + dx[i];
                var Y = u.y + dy[i];
                if(X < 0 || Y < 0 || X > ppCanvasWidth || Y > ppCanvasHeight || ppVisit[Y * ppCanvasWidth + X])continue;
                ppVisit[Y * ppCanvasWidth + X] = true;
                if(Math.abs(ppImgData.data[(Y * ppCanvasWidth + X) * 4] - R) > threshold)continue;
                if(Math.abs(ppImgData.data[(Y * ppCanvasWidth + X) * 4 + 1] - G) > threshold)continue;
                if(Math.abs(ppImgData.data[(Y * ppCanvasWidth + X) * 4 + 2] - B) > threshold)continue;
                ppImgData.data[(Y * ppCanvasWidth + X) * 4] = fillR;
                ppImgData.data[(Y * ppCanvasWidth + X) * 4 + 1] = fillG;
                ppImgData.data[(Y * ppCanvasWidth + X) * 4 + 2] = fillB;
                ppQueue.push(new ppPoint(X, Y));
            }
        }
        context.putImageData(ppImgData, 0, 0);
    });

 

posted @ 2015-10-31 23:56  philippica  阅读(1408)  评论(1编辑  收藏  举报