使用HTML5画布掩盖putImageData?

Jam*_*rgy 6 javascript canvas image-processing

我想从现有图像中获取不规则形状的部分,并使用HTML5画布将其渲染为Javascript中的新图像.因此,只会复制多边形边界内的数据.我提出的方法涉及:

  1. 在新画布中绘制多边形.
  2. 使用创建掩码 clip
  3. 使用getImageData(矩形)复制原始画布中的数据
  4. 使用将数据应用于新画布 putImageData

它不起作用,整个矩形(例如来自边界外的源的东西)仍然出现.这个问题解释了为什么:"规范说putImageData不会受剪裁区域的影响." 党!

我也尝试绘制形状,设置context.globalCompositeOperation = "source-in",然后使用putImageData.相同的结果:没有应用蒙版.我怀疑是因为类似的原因.

关于如何实现这一目标的任何建议?这是我正在进行的工作的基本代码,以防我不知道自己要做什么.(不要太努力地调试它,它会从使用很多不在这里的函数的代码中清理/提取,只是试图显示逻辑).

 // coords is the polygon data for the area I want
   context = $('canvas')[0].getContext("2d");
   context.save();
   context.beginPath();
   context.moveTo(coords[0], coords[1]);
   for (i = 2; i < coords.length; i += 2) {
     context.lineTo(coords[i], coords[i + 1]);
   }
   //context.closePath();
   context.clip();

   $img = $('#main_image');
   copy_canvas = new_canvas($img); // just creates a new canvas matching dimensions of image
   copy_ctx = copy.getContext("2d");

   tempImage = new Image();
   tempImage.src = $img.attr("src");
   copy_ctx.drawImage(tempImage,0,0,tempImage.width,tempImage.height);

  // returns array x,y,x,y with t/l and b/r corners for a polygon
  corners = get_corners(coords)
  var data = copy_ctx.getImageData(corners[0],corners[1],corners[2],corners[3]);
  //context.globalCompositeOperation = "source-in";
  context.putImageData(data,0,0);
  context.restore();
Run Code Online (Sandbox Code Playgroud)

Cas*_*jne 10

不要用putImageData,

只需在内存画布中使用document.createElement创建一个额外的掩码,并将其应用于a drawImage()globalCompositeOperation函数(取决于您选择正确模式所需的顺序;

在这里类似代码在这里(介意CasparKleijne.Canvas.GFX.Composite功能)