前端canvas实现签名功能,可以横屏/竖屏签名

页面展示效果,点保存后生成图片链接

图片链接展示效果

这里只展示了竖屏签名效果,横屏自己粘贴代码测试

css

.box {width: 98%;display: flex;flex-direction: column;margin: auto;}
.canvasbox {width: 100%;border: 1px solid #bbb;margin: 0 auto;overflow: hidden;}
canvas {background: #f4f5f7;}
.box2 {width: 50%;margin: 5px auto;display: flex;justify-content: space-between;}
.btn {width: 70px;height: 30px;line-height: 30px;line-height: 30px;border: 1px solid #bbb;text-align: center;border-radius: 3px;margin-top: 10px;}

 

html

<div class="box" id="myBox">
    <div class="canvasbox" id="myDiv">
        <canvas id="signatureCanvas"></canvas>
    </div>
    <div class="box2">
        <div class="btn" onclick="clearSignature()">清除</div>
        <div class="btn" onclick="saveSignature()">保存</div>
    </div>
</div>

 

js

var myDiv = document.getElementById('myDiv');
var myBox = document.getElementById('myBox');
// var mySpan = document.getElementById('mySpan');
var screenHeight = 0, screenWidth = 0;


const canvas = document.getElementById('signatureCanvas');
const ctx = canvas.getContext('2d');

let isDrawing = false;
let lastX = 0;
let lastY = 0;

canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', stopDrawing);
canvas.addEventListener('touchcancel', stopDrawing);

function draw(e) {
        if (!isDrawing) return;
        e.preventDefault();

        const currentX = e.touches[0].clientX - e.target.offsetLeft;
        const currentY = e.touches[0].clientY - e.target.offsetTop;

        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(currentX, currentY);
        ctx.stroke();
        [lastX, lastY] = [currentX, currentY];
}

function startDrawing(e) {
        drawCanvas = true
        isDrawing = true;
        [lastX, lastY] = [e.touches[0].clientX - e.target.offsetLeft, e.touches[0].clientY - e.target.offsetTop];
}

function stopDrawing() {
        isDrawing = false;
}

// 清除签字
function clearSignature() {
        drawCanvas = false
        ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function saveSignature() {
    if (!drawCanvas) {
            alert('请手写签名')
            return
    }
    const dataURL = canvas.toDataURL('image/png');  // 转换为 PNG 格式的图像数据
        // 将 dataURL 提交给后端进行处理
        console.log(dataURL)
        // fetch('/saveSignature', {  //提交接口,随便写的(改成对应的接口)
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json'
        //     },
        //     body: JSON.stringify({ signatureDataURL: dataURL })
        // }).then(response => {
        //     // 处理响应
        // }).catch(error => {
        //     // 处理错误
        // });

}
var tempCanvas = document.createElement('canvas');
var tempCtx = tempCanvas.getContext('2d');

function orient() {
        if (window.orientation == 0 || window.orientation == 180) {
            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');

            // 保存当前画布内容到临时画布
            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;
            tempCtx.drawImage(canvas, 0, 0);
            screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            screenWidth = window.innerWidth || document.documentElement.innerWidth || document.body.innerWidth;
            myDiv.style.height = screenHeight * 0.8 + 'px';
            canvas.setAttribute("height", screenHeight * 0.8);
            canvas.setAttribute("width", screenWidth);

            ctx.translate(canvas.width / 2, canvas.height / 2); // 设置中心点
            ctx.rotate((90 * Math.PI) / 180); // 逆时针旋转90度
            ctx.drawImage(tempCanvas, -tempCanvas.width / 2, -tempCanvas.height / 2);

            // 恢复画布
            ctx.rotate((-90 * Math.PI) / 180);
            ctx.translate(-canvas.width / 2, -canvas.height / 2);
            console.log('竖屏');
            alert("竖屏")

        } else {
            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');

            screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            screenWidth = window.innerWidth || document.documentElement.innerWidth || document.body.innerWidth;
            myDiv.style.height = screenHeight * 0.8 + 'px';

            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;
            tempCtx.drawImage(canvas, 0, 0);
            canvas.setAttribute("height", screenHeight * 0.8);
            canvas.setAttribute("width", screenWidth);

            ctx.translate(canvas.width / 2, canvas.height / 2); // 设置中心点
            ctx.rotate((-90 * Math.PI) / 180); // 顺时针旋转90度
            ctx.drawImage(tempCanvas, -tempCanvas.width / 2, -tempCanvas.height / 2);

            // 恢复画布
            ctx.rotate((90 * Math.PI) / 180); // 恢复旋转角度
            ctx.translate(-canvas.width / 2, -canvas.height / 2); // 恢复绘图原点
            console.log('横屏');
            alert("横屏")
        }
        myBox.style.height = screenHeight + 'px';
    }
//页面初次加载
window.onload = function () {
    orient();
}
//页面添加转屏事件          
// window.addEventListener('orientationchange', function () {
//     console.log(2222);
//     orient();
// });
//浏览器变化
window.onresize = function () {
        orient();
};

 

posted @ 2023-10-07 10:44  srqsl  阅读(267)  评论(0编辑  收藏  举报