javascript - 通过 JavaScript 的魔棒工具

标签 javascript image-processing

我将开始一个新项目,该项目要求我根据多边形选择裁剪图像。挑战在于让前端用户能够快速选择图像中的区域,然后对其进行裁剪。为了使用户的过程更容易,我正在考虑提供一些类似于 Photoshop 中的魔术棒工具的功能。

我找到了这个库 - https://github.com/Tamersoul/magic-wand-js

这工作正常,但只让我选择该区域一次。

我的问题是,是否可以添加多个选择的功能以及从已选择的区域中删除一个选择。

检查这个演示 fiddle ,看看我指的是什么 - jsfiddle(dot)net/Tamersoul/dr7Dw/

最佳答案

github.com Magic-Wand-js

jsbin.com Demo

$(function() {
  var colorThreshold = 15,
      blurRadius = 5,
      simplifyTolerant = 0,
      simplifyCount = 30,
      hatchLength = 4,
      hatchOffset = 0,
      imageInfo = null,
      cacheInd = null,
      cacheInds = [],      
      downPoint = null,
      mask = null,
      masks = [],
      allowDraw = false,
      currentThreshold = colorThreshold;

  $('#upload').on('change', function () {
    var inp = this;
    if (inp.files && inp.files[0]) {
      var reader = new FileReader();
      
      reader.onload = function (e) {
        var img = $('#test');
        img.attr('src', e.target.result);
        
        img.on('load', function() {
          resetCache();
          var canvas = $('#canvas')[0];
          imageInfo = {
            width: img.width(),
            height: img.height(),
            context: canvas.getContext("2d")
          };          
          canvas.width = imageInfo.width;
          canvas.height = imageInfo.height;
          var tempCanvas = document.createElement('canvas'),
              tempCtx = tempCanvas.getContext("2d");
          tempCanvas.width = imageInfo.width;
          tempCanvas.height = imageInfo.height;
          tempCtx.drawImage(img[0], 0, 0);
          imageInfo.data = tempCtx.getImageData(0, 0, imageInfo.width, imageInfo.height).data;
        });
      };
      reader.readAsDataURL(inp.files[0]);
    }
  });

  $('#blur').on('change keyup', function () {
    blurRadius = Number($(this).val()) || 0;
    magic();
  });

  $('#threshold').on('change keyup', function () {
    currentThreshold = Number($(this).val()) || 0;
    magic();
  });

  $('#canvas').on('click', function (e) {
    var p = $(e.target).offset(),
        x = Math.round((e.clientX || e.pageX) - p.left),
        y = Math.round((e.clientY || e.pageY) - p.top);    
    downPoint = { x: x, y: y };    
    magic();
  });

  var magic = function () {
    if (imageInfo) {
      var image = {
        data: imageInfo.data,
        width: imageInfo.width,
        height: imageInfo.height,
        bytes: 4
      };
      mask = MagicWand.floodFill(image, downPoint.x, downPoint.y, currentThreshold);
      mask = MagicWand.gaussBlurOnlyBorder(mask, blurRadius);
      masks.push(mask);
      cacheInds.push(MagicWand.getBorderIndices(mask));
      drawBorder(true);
    }
  };
  
  var drawBorder = function () {
    if (masks.length) {

      var x, y, k, i, j, m,
          w = imageInfo.width,
          h = imageInfo.height,
          ctx = imageInfo.context,
          imgData = ctx.createImageData(w, h),
          res = imgData.data;
      
      ctx.clearRect(0, 0, w, h);
      
      for (m = 0; m < masks.length; m++) {
        
        cacheInd = cacheInds[m];
        
        for (j = 0; j < cacheInd.length; j++) {
          i = cacheInd[j];
          x = i % w; // calc x by index
          y = (i - x) / w; // calc y by index
          k = (y * w + x) * 4; 
          if ((x + y + hatchOffset) % (hatchLength * 2) < hatchLength) { 
            // detect hatch color 
            res[k + 3] = 255; // black, change only alpha
          } else {
            res[k] = 255; // white
            res[k + 1] = 255;
            res[k + 2] = 255;
            res[k + 3] = 255;
          }
        }
      }
      ctx.putImageData(imgData, 0, 0);
    }
  };

  setInterval(function () {
    hatchOffset = (hatchOffset + 1) % (hatchLength * 2);
    drawBorder();
  }, 100);
  
  $('#trace').on('click', function () {
    var ctx = imageInfo.context;
    ctx.clearRect(0, 0, imageInfo.width, imageInfo.height);
    for (var m = 0; m < masks.length; m++) {
      // draw contours
      var i, j, ps, cs = MagicWand.traceContours(masks[m]);
      cs = MagicWand.simplifyContours(cs, simplifyTolerant, simplifyCount);
      //inner
      ctx.beginPath();
      for (i = 0; i < cs.length; i++) {
        if (cs[i].inner) {
          ps = cs[i].points;
          ctx.moveTo(ps[0].x, ps[0].y);
          for (j = 1; j < ps.length; j++) {
            ctx.lineTo(ps[j].x, ps[j].y);
          }
        }
      }
      ctx.strokeStyle = 'red';
      ctx.stroke();
      //outer
      ctx.beginPath();
      for (i = 0; i < cs.length; i++) {
        if (!cs[i].inner) {
          ps = cs[i].points;
          ctx.moveTo(ps[0].x, ps[0].y);
          for (j = 1; j < ps.length; j++) {
            ctx.lineTo(ps[j].x, ps[j].y);
          }
        }
      }
      ctx.strokeStyle = 'blue';
      ctx.stroke(); 
    }
    resetCache();
  });
    
  var resetCache = function () {
    mask = null;
    masks = [];
    cacheInds = [];
  };
  
});
#display * {
  cursor: crosshair;
  position: absolute;
}
<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdn.jsdelivr.net/npm/magic-wand-js@1.0.0/js/magic-wand.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
  </head>

  <body>
    <div id="controls">
      <input id="upload" type="file" accept="image/*"/>
      <p>Blur radius
        <input value="5" id="blur" type="number"/>
      </p>
      <p>Threshold
        <input value="15" id="threshold" type="number"/>
      </p>
      <button id="trace">Trace</button>
    </div>
    <div id="display">      
      <img id="test"/>
      <canvas id="canvas"></canvas>
    </div>  
  </body>

</html>

关于javascript - 通过 JavaScript 的魔棒工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699104/

相关文章:

c++ - 加载、裁剪和保存 jpg C++

python - 使用 Python OpenCV 读取 JPG 彩色图像并将图像保存为原始或二进制文件

javascript - 如何使用 onchange="function(this.value)

javascript - Angular POST 到 Node 服务器

javascript - MapboxGL Javascript API : displaying popup for all markers on map not working on multiple layers

c++ - 图像的边缘检测

javascript - 从 JavaScript POST 重新加载 Razor 页面

javascript - 覆盖 Object.observe() 中的属性

image-processing - 图像边缘检测

c++ - OpenCV 更好地检测红色?