自动将 HTML5 画布裁剪为内容

Automatically Crop HTML5 canvas to contents(自动将 HTML5 画布裁剪为内容)

本文介绍了自动将 HTML5 画布裁剪为内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这是我的画布,上面画着一张邪恶的脸.我想使用 toDataURL() 将我的邪恶面孔导出为 PNG;但是,整个画布都被光栅化了,包括邪恶的脸和画布边缘之间的空白".

Let's say this is my canvas, with an evil-looking face drawn on it. I want to use toDataURL() to export my evil face as a PNG; however, the whole canvas is rasterised, including the 'whitespace' between the evil face and canvas edges.

+---------------+
|               |
|               |
|     (.Y. )    |
|      /_       |
|     \____/    |
|               |
|               |
+---------------+

将我的画布裁剪/修剪/收缩包装到其内容的最佳方法是什么,所以我的 PNG 不大于面部的边界框",如下所示?最好的方法似乎是缩放画布,但假设内容是动态的......?我确信应该有一个简单的解决方案,但它正在逃避我,有很多谷歌搜索.

What is the best way to crop/trim/shrinkwrap my canvas to its contents, so my PNG is no larger than the face's 'bounding-box', like below? The best way seems to be scaling the canvas, but supposing the contents are dynamic...? I'm sure there should be a simple solution to this, but it's escaping me, with much Googling.

+------+
|(.Y. )|
| /_   |
|\____/|
+------+

谢谢!

推荐答案

已编辑(参见 评论)

function cropImageFromCanvas(ctx) {
  var canvas = ctx.canvas, 
    w = canvas.width, h = canvas.height,
    pix = {x:[], y:[]},
    imageData = ctx.getImageData(0,0,canvas.width,canvas.height),
    x, y, index;

  for (y = 0; y < h; y++) {
    for (x = 0; x < w; x++) {
      index = (y * w + x) * 4;
      if (imageData.data[index+3] > 0) {
        pix.x.push(x);
        pix.y.push(y);
      } 
    }
  }
  pix.x.sort(function(a,b){return a-b});
  pix.y.sort(function(a,b){return a-b});
  var n = pix.x.length-1;

  w = 1 + pix.x[n] - pix.x[0];
  h = 1 + pix.y[n] - pix.y[0];
  var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);

  canvas.width = w;
  canvas.height = h;
  ctx.putImageData(cut, 0, 0);

  var image = canvas.toDataURL();  //open cropped image in a new window
  var win=window.open(image, '_blank');
  win.focus();
}

这篇关于自动将 HTML5 画布裁剪为内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:自动将 HTML5 画布裁剪为内容

基础教程推荐