javascript - html5 canvas删除垂直/水平线像素值

标签 javascript html canvas

我正在为相框实现接缝雕刻算法。

https://en.wikipedia.org/wiki/Seam_carving

我知道这个算法不是很好,因为它从图片中切出一条直缝,但好消息是我这样做是为了“相框”,所以你可以想象它会工作得很好。

因此,如果图像宽度为 100 像素,我想删除第 50 像素处的垂直线。那么宽度将为 99 像素。

这是伪代码,我删除了之前的代码尝试

  1. 将图像加载到 Canvas 上。
  2. 删除一条宽度为 1 像素、高度等于加载图像的垂直线。如果该图像的宽度等于 100,则现在为 99。
  3. 获取新处理图像的 Base64 编码字符串。

我想要做的是删除一条宽度为1像素且高度等于图像的垂直线,然后将图像绘制到 Canvas 上并获得base64编码的图像。

最佳答案

您可以使用原始图像作为源,然后将 Canvas 设置为最终尺寸,例如:

var img=new Image; img.onload=carve; img.src = "//i.stack.imgur.com/OqB5r.jpg";

function carve() {
  var ctx = c.getContext("2d");
  var cut = 50;        // we remove [50, 50 + carveWidth>, in this case
  var carveWidth = 16; // exaggerated to show noticeable change
  
  // set final size of canvas:
  c.width = this.width - carveWidth;
  c.height = this.height;
  
  // draw in first half using clip arguments of drawImage()
  ctx.drawImage(this, 0, 0, cut, this.height, 0, 0, cut, this.height);

  // draw in second half, notice we skip cut+carve for source, but not for dest.
  ctx.drawImage(this, cut + carveWidth, 0, this.width, this.height,
                      cut             , 0, this.width, this.height);
                      
  // save out canvas
}
canvas {border:1px solid red} /* to show actual canvas size */
<canvas id=c></canvas>

对于算法,您需要执行类似的操作,但使用雕刻路径作为前半部分的掩码:

  • 以目标尺寸绘制图像(完整)
  • 使用复合模式通过封闭路径剪掉后半部分来消除不规则的声音
  • 使用复合模式destination-over
  • 在图像中绘制减去接缝的偏移量 - 这将在前半部分后面绘制,从而形成完整的图像

对每个接缝重复此操作。

关于javascript - html5 canvas删除垂直/水平线像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258781/

相关文章:

jquery - 无法通过 jQuery 更新 Canvas

php - 将 JSON 对象附加到 URL 末尾

javascript - 加载此元素后立即将类名添加到元素

javascript - 在 <p> 中动态创建一个 <div>

javascript - 在 p5.js 中创建圆 Angular Canvas

javascript - 用 canvas/JS 高亮图像区域

javascript - ngAnimate 在 AngularJS 1.6.4 中停止工作

javascript - 在多维数组中查找值的最快方法?

javascript - 使用 jQuery 和 CSS 根据另一个 div 的文本更改背景颜色

html - 如何将我的网站居中?