canvas 裁剪签名图片 去除多余的空白

xiaoxiao2021-02-27  339

var canvas = document.createElement("canvas"); canvas.width = sWidth; canvas.height = sHeight; var context= canvas.getContext("2d"); context.font = "20px Georgia"; context.textAlign = 'center'; //文本水平对齐方式 context.textBaseline = 'bottom'; //文本垂直方向,基线位置 //context.fillText(name, sWidth / 2, 50); context.drawImage(signImg, 50, 50); var imgData = context.getImageData(0, 0, canvas.width, canvas.height).data; var lOffset = canvas.width, rOffset = 0,tOffset = canvas.height, bOffset = 0; for (var i = 0; i < canvas.width; i++) { for (var j = 0; j < canvas.height; j++) { var pos = (i + canvas.width * j) * 4 if (imgData[pos] == 255 || imgData[pos + 1] == 255 || imgData[pos + 2] == 255 || imgData[pos + 3] == 255) { bOffset = Math.max(j, bOffset); // 找到有色彩的最下端 rOffset = Math.max(i, rOffset); // 找到有色彩的最右端 tOffset = Math.min(j, tOffset); // 找到有色彩的最上端 lOffset = Math.min(i, lOffset); // 找到有色彩的最左端 } } } lOffset++; rOffset++; tOffset++; bOffset++; var c = document.createElement("canvas"); c.width = rOffset-lOffset+100; c.height = bOffset-tOffset+100; var ctx = c.getContext("2d"); ctx.font = "20px Georgia"; ctx.drawImage(signImg, lOffset-100, tOffset-100, c.width, c.height, 0, 0, c.width, c.height);
转载请注明原文地址: https://www.6miu.com/read-3622.html

最新回复(0)