签名板上下载的画布周围的空白处

问题描述 投票:0回答:1

我已经在我的网站上实现了签名pad.js。我想在绘制的签名周围修剪空白。我现在正在修剪画布周围未使用的透明区域。我尝试将画布背景设为白色。则此代码无法检测到画点边界。

但是,我需要制作背景白色

这是我现在要得到的:-

enter image description here(签名)

====>

enter image description here(修剪后)

我正在使用以下代码来修剪签名周围的透明背景:

function trimCanvas(c) {
    var ctx = c.getContext('2d'),
        copy = document.createElement('canvas').getContext('2d'),
        pixels = ctx.getImageData(0, 0, c.width, c.height),
        l = pixels.data.length,
        i,
        bound = {
            top: null,
            left: null,
            right: null,
            bottom: null
        },
        x, y;

    // Iterate over every pixel to find the highest
    // and where it ends on every axis ()
    for (i = 0; i < l; i += 4) {
        if (pixels.data[i + 3] !== 0) {
            x = (i / 4) % c.width;
            y = ~~((i / 4) / c.width);

            if (bound.top === null) {
                bound.top = y;
            }

            if (bound.left === null) {
                bound.left = x;
            } else if (x < bound.left) {
                bound.left = x;
            }

            if (bound.right === null) {
                bound.right = x;
            } else if (bound.right < x) {
                bound.right = x;
            }

            if (bound.bottom === null) {
                bound.bottom = y;
            } else if (bound.bottom < y) {
                bound.bottom = y;
            }
        }
    }

    // Calculate the height and width of the content
    var trimHeight = bound.bottom - bound.top,
        trimWidth = bound.right - bound.left,
        trimmed = ctx.getImageData(bound.left, bound.top, trimWidth, trimHeight);

    copy.canvas.width = trimWidth;
    copy.canvas.height = trimHeight;
    copy.putImageData(trimmed, 0, 0);

    // Return trimmed canvas
    return copy.canvas;
}
javascript digital-signature signaturepad
1个回答
0
投票

使用此代码

signaturePad.removeBlanks(); var data = signaturePad.toDataURL('image/png');

首先删除空格,然后您可以将其转换为数据图像。注意:只有我才编译,尚未测试

© www.soinside.com 2019 - 2024. All rights reserved.