自动裁剪HTML5画布到内容

编程入门 行业动态 更新时间:2024-10-27 01:26:26
本文介绍了自动裁剪HTML5画布到内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 假设这是我的画布,画上了一张邪恶的脸。我想用 toDataURL()将我的恶脸导出为PNG;然而,整个画布都是光栅化的,包括邪恶面孔和画布边缘之间的空白。

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

裁剪/修剪/缩小我的画布到其内容的最佳方式是什么?因此,我的PNG不会比脸部的边界框更大,如下所示?最好的方式似乎是缩放画布,但假设内容是动态的......?我相信应该有一个简单的解决方案,但它逃避我,用谷歌搜索。

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

谢谢!

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

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. ) | | /_ | | \____/ | | | | | +---------------+

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. )| | /_ | |\____/| +------+

Thanks!

解决方案

function cropImageFromCanvas(ctx, canvas) { var 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 = pix.x[n] - pix.x[0]; h = 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(); var win=window.open(image, '_blank'); win.focus(); }

更多推荐

自动裁剪HTML5画布到内容

本文发布于:2023-08-02 03:47:41,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:画布   内容

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!