지식 창고

canvas tag에 draw한 이미지 png로 다운로드하기 본문

프로그래밍/HTML, CSS

canvas tag에 draw한 이미지 png로 다운로드하기

Lucky-John 2021. 8. 28. 12:23

1. 크롬 브라우저에서 로컬 파일 테스트를 위해서는 로컬 파일 접근 오류를 해결해야 한다.

 참고 : https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=biud436&logNo=220532711979  

 

크롬 브라우저로 테스트 할 때 로컬 파일 접근 오류 해결하기 - RPG Maker MV

"... 크롬..." 답변했던 질문의 해결법을 블로그에 정리해서 올립니다. 인터넷 연결없이 로컬에서 html 파...

blog.naver.com

우선,  실행되어 있는 크롬 창을 모두 닫고,
작업 관리자에서도 실행되어 있는 크롬 task와 service를 모두 닫는다.
이후, 크롬 실행파일을 바로가기 아이콘을 만든다.
 그 다음에 바로가기 아이콘 속성 중 대상 칸에 -allow-file-access-from-files 을 추가한다.
해당 크롬 바로가기 아이콘을 실행하여 크롬을 실행한다.

 

2. 테스트 페이지 만들기

참고 파일 :

canvasSave22.html
0.00MB
html2canvas.js
0.42MB
savePng.css
0.00MB
SaveCanvas.zip
1.17MB


<!DOCTYPE HTML>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>p151_3.2사각형그리기</title>
    <script src="http://code.jquery.com/jquery-1.12.4.js"></script>
    <link rel="stylesheet" href="savePng.css">
</head>
<body>
    <button id="downloadFundusImage" type="button" href="" 
            download="my_painting.png" onclick="downImg()">div / canvas 영역 이미지로 저장</button>
    <p>
    <div id="tmpImgDiv">
        <canvas id="FundusCanvas" width="550" height="550">canvas</canvas>
    </div>
    <div>
         <img id="uploadPreview" src="" width="550" height="550">
         <!-- <img id="myImage" src="" width="550" height="550"> -->
     </div>
    <script>
        var isDrawing=false;
        var canvas = $("#tmpImgDiv #FundusCanvas").get(0);
        var ctx = canvas.getContext("2d");

       canvas.addEventListener('mousemove', event =>
               draw(event.offsetX, event.offsetY)
       );
       canvas.addEventListener('mousedown', () => isDrawing = true);
       canvas.addEventListener('mouseup', () => isDrawing = false);

      // 새로운 이미지 객체를 만듬
      var img = new Image();
      img.crossOrigin="anonymous";   <= 매우 중요함. 이 crossOrigin 설정이 되어야 로컬 파일 접근이 가능함. !!!

      img.onload = function() {
        alert("image on load");
        ctx.drawImage(img, 5, 5); 

       draw_overlay();
     }
     // 이미지 URL
     img.src = 'fundus_os.png';

      function draw_overlay() {
          // 내부가 채워진 사각형 그리기
          ctx.fillStyle = "magenta";      // 내부 채울 색상
          ctx.fillRect(20,20,100,100);    // x:20, y:20 위치에서 폭과 높이가 100인 "내부가 색으로 채워진" 사각형 그리기.
          ctx.strokeRect(20,20,150,150);  // x:20, y:20 위치에서 폭과 높이가 150인 "선만 있는" 사각형 그리기.
          ctx.fillStyle = "green";        // color / hex / rgba() / gradient / pattern - 채우기 가능
          ctx.fillRect(150,150,50,50);
          ctx.strokeRect(150,150,50,50);

         // 내부를 사각형으로 지우기
         ctx.lineWidth = 10;
         ctx.strokeStyle = "red";
         ctx.fillStyle = "blue";
         ctx.fillRect(250,250,200,200);
         ctx.strokeRect(250,250,200,200);
         ctx.clearRect(270,270,100,50);  // 지울 사각형 위치와 크기
     }

    function draw(x, y) {
         if (isDrawing) {
             ctx.beginPath();
             ctx.arc(x, y, 10, 0, Math.PI*2);
             ctx.closePath();
             ctx.fill();
        }
   }
    
   //이미지(png)로 다운로드
   function downImg(){
       html2canvas($("#tmpImgDiv #FundusCanvas")[0]).then(function(canvas) { 
            var myImage = canvas.toDataURL(); 
            var img_b64 = canvas.toDataURL('image/png');
            var png = img_b64.split(',')[1];
            var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});
            //$('#myImage').attr("src",  'fundus_os.png');
            downloadURI2(canvas);
            downloadURI(myImage, "fundus_my.png")  
      });
    }

     function downloadURI(uri, name){
        var link = document.createElement("a")
        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();
     }
  
     function downloadURI2(canvas) {
         var img_b64 = canvas.toDataURL('image/png');
         var png = img_b64.split(',')[1];
         var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

         var fr = new FileReader();
         fr.onload = function ( oFREvent ) {
             var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
             v = atob(v);
             var good_b64 = btoa(decodeURIComponent(escape(v)));
             //document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
            $("#uploadPreview").attr("src", "data:image/png;base64," + good_b64);
        };
        fr.readAsDataURL(the_file);
     }  
    </script>
    <script src="html2canvas.js"></script>
</body>
</html>


html {
  padding: 10px 20px;
  font-family: sans-serif;
}
canvas {
  background: #fff;
  border: 1px dashed;
}
a {
  display: inline-block;
  background: #69c;
  color: #fff;
  padding: 5px 10px;
}


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

canvas prog graph draw  (0) 2021.09.28
custom button  (0) 2021.09.21
유용한 팁  (0) 2021.09.15
크롬 WEB 디버깅 방법  (0) 2021.08.29
HTML 컬러 차트  (0) 2021.08.11
Comments