728x90
반응형

canvas 사용하기

html 기본 element인 canvas를 사용하여 서명하고 api로 보내주는 코드를 작성해봄

 


html 코드 

<html>
    <head>
        <title>canvas</title>
        <style>
            /* Add any necessary CSS styles here */
            #canvasModal {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.5);
                z-index: 9999;
            }
        
            #canvasContainer {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: #fff;
                padding: 20px;
            }
        
            #canvas {
                border: 1px solid #ccc;
            }
        </style>
    </head>
    <body>
        <div id="canvasModal">
            <div id="canvasContainer">
                <canvas id="canvas" width="400" height="200"></canvas>
                <button id="saveButton">저장</button>
                <button id="erase">지우기</button>
                <button id="closeButton">닫기</button>
            </div>
        </div>
    </body>
    </html>

 


javascript 코드

const signatureButton = document.getElementById('signatureButton');
const canvasModal = document.getElementById('canvasModal');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
let isDrawing = false;

// Handle button click event
function handleSignatureClick(shipSeq) {
    canvasModal.style.display = 'block';
    context.clearRect(0, 0, canvas.width, canvas.height);
    isDrawing = false;
}

// mouse로 그리기 & 터치로 그리기 이벤트 추가
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', endDrawing);
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', endDrawing);

// Start drawing
function startDrawing(event) {
    isDrawing = true;
    const { offsetX, offsetY } = getCoordinates(event);
    context.beginPath();
    context.moveTo(offsetX, offsetY);
}

// Draw on the canvas
function draw(event) {
    if (!isDrawing) return;
    event.preventDefault();
    const { offsetX, offsetY } = getCoordinates(event);
    context.lineTo(offsetX, offsetY);
    context.stroke();
}

// End drawing
function endDrawing() {
    isDrawing = false;
}

// Get the coordinates of the event (mouse or touch)
function getCoordinates(event) {
let offsetX, offsetY;
if (event.type.startsWith('mouse')) {
    offsetX = event.offsetX;
    offsetY = event.offsetY;
} else if (event.type.startsWith('touch')) {
    const rect = canvas.getBoundingClientRect();
    offsetX = event.touches[0].clientX - rect.left;
    offsetY = event.touches[0].clientY - rect.top;
}
return { offsetX, offsetY };
}


// Handle save button click event
const saveButton = document.getElementById('saveButton');
saveButton.addEventListener('click', () => {
    const signatureImage = canvas.toDataURL('image/png');
    // Perform further processing with the signature image data
    console.log('Signature image:', signatureImage);

    // Close the canvas modal
    canvasModal.style.display = 'none';

    const file = dataURLtoFile(signatureImage, 'sign_image.png');
    let formData = new FormData();
    formData.append('file', file);

    const headers = {
        'Content-Type': 'multipart/form-data',
    };

    // Send image upload request to the server using Fetch
    axios.put('apiURL', formData, { headers })
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

});

// url -> 파일로 변경하기
function dataURLtoFile(dataURL, filename) {
    const arr = dataURL.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

// 닫기 이벤트
const closeButton = document.getElementById('closeButton');
closeButton.addEventListener('click', () => {
    canvasModal.style.display = 'none';
});

// 지우기 이벤트
const eraseButton = document.getElementById('erase');
eraseButton.addEventListener('click', eraseCanvas);
function eraseCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}
반응형

'프로그래밍 > HTML' 카테고리의 다른 글

input 태그에 브라우저 자동 완성 기능 해제하기  (0) 2021.12.10
img 태그 onerror 처리 방법  (0) 2021.10.29
Java, Html, Jsp에서의 주석처리 방법  (2) 2021.08.27
07.02(semantic tags)  (0) 2020.07.02
09.11(form)  (0) 2020.06.11
복사했습니다!