Canvas 에서 크기 맞춰서 출력해주기

아기코딩단2·2022년 8월 4일
0
<!--상위 코드 생략-->
toCanvas.addEventListener('click', function toCanvas() {
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d", { alpha: true });
        console.log('ctx::::::::::', ctx);
        var img = document.getElementById("output");
        // if 문 돌려서 여기서 처리해주면 될 듯
        console.log("cHeight::::::::::", c.width);
        console.log("cHeight::::::::::", c.height);

        console.log('imgWidht::::::', img.offsetWidth);
        console.log('imgHeight::::::', img.offsetHeight);

        
        let iw, ih; // ofsetWidth 나 width는 안바뀌는 속성이라서 변수에 담아주고 바궈야함
        // 즉 img.offsetWidth = 100; <= 이렇게 해도 안먹힘 그래서 변수 생성 후 거기다가 2048을 넣어줌 

        if (img.offsetWidth >= img.offsetHeight) {
            iw = 2048;
            ih = img.offsetHeight / (img.offsetWidth / iw);
        } else {
            ih = 2048;
            iw = img.offsetWidth / (img.offsetHeight / ih);
        }

        console.log('ifWidth입니다::::::', iw);
        console.log('ifHeight입니다:::::::::', ih);

        const x = (iw - ih)/2;
        const y = (iw - ih)/2;

        // ctx.translate(0, 0);
        ctx.drawImage(img, x, y, iw, ih);
        //console.log(ctx.drawImage());
    });


비율 맞추면서 줄어들게 성공 ㅎㅎㅎ

profile
레거시 학살자

0개의 댓글