Coding/JavsScript 삽질기2022. 1. 19. 01:08

유튜브에서 회전하는 도넛 영상을 보고, 회전하는 구를 그려 보았다.

Sphere

1. 난해하게 만든 전체 소스는 아래와 같다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sphere</title>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        canvas {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
<div align='center'>
    <canvas id="canvas"></canvas>
</div>
<script language="JavaScript">
    // Start: 2022.01.18
    // Update: 2022.01.19

    let cvs;
    let canvas;
    let bufCanvas;
    let bufCtx;
    let thetaX = 0;
    let thetaZ = 0;

    let SIN = [];
    let COS = [];

    function InitValue() {
        for (let i = 0; i < 628; i++) {
            SIN[i] = Math.sin(i / 100);
            COS[i] = Math.cos(i / 100);
        }
    }
    
    function InitCanvas() {
        height = window.innerHeight;
        width = window.innerWidth;

        console.log(">Width:", width);
        console.log(">Heigth:", height);

        canvas = document.getElementById("canvas");
        canvas.width = width;
        canvas.height = height;
        cvs = canvas.getContext("2d");

        bufCanvas = document.createElement("canvas");
        bufCanvas.width = canvas.width;
        bufCanvas.height = canvas.height;
        bufCtx = bufCanvas.getContext("2d");
    }

    function drawCircle(x, y, c, r) {
        bufCtx.beginPath();
        bufCtx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
        bufCtx.strokeStyle = "rgb(255, 255, 255)";
        bufCtx.arc(x, y, r, 0, Math.PI * 2);
        bufCtx.stroke();
        bufCtx.fill();
        bufCtx.closePath();
    }

    function _draw() {
        let maxSize = canvas.height < canvas.width ? canvas.height : canvas.width;
        let dimen = 8;
        let ox = canvas.width / 2;
        let oy = canvas.height / 2;
        let R1 = maxSize/20;
        let ZZ1 = maxSize * 1000 * 0.4 / R1;

        let points = [];

        for (let i = 0; i < 628; i += dimen) {
            let a = COS[i];
            let b = SIN[i];

            for (let j = 0; j < 628; j += dimen) {
                let c = COS[j];
                let d = SIN[j];
                let e = COS[thetaX];
                let f = SIN[thetaX];
                let g = COS[thetaZ];
                let h = SIN[thetaZ];

                let k = b * R1 * e - a * R1 * d * f;
                let x4 = a * R1 * c * g - k * h;
                let y4 = a * R1 * c * h + k * g;
                let z4 = ZZ1 / (1000 + b * R1 * f + a * R1 * d * e);
                let light = (b * f + a * d * e);

                if (light > 0) {
                    let color = Math.round(light * 255);
                    let xp = Math.floor(x4 * z4 + ox);
                    let yp = Math.floor(-y4 * z4 + oy);
                    points.push([xp, yp, 255-color]);
                }
            }
        }

        bufCtx.strokeStyle = "black";
        bufCtx.fillStyle = "black";
        bufCtx.fillRect(0, 0, canvas.width, canvas.height);
        points.forEach(e => drawCircle(e[0], e[1], e[2], 1));

        thetaX = (thetaX + 2) % 629;
        thetaZ = (thetaZ + 2) % 629;
    }

    function OnDraw() {
        let startTime = new Date();
        _draw();

        cvs.clearRect(0, 0, canvas.width, canvas.height);
        cvs.drawImage(bufCanvas, 0, 0);

        console.log("Elapsed time: " + (new Date() - startTime));
    }


    function onLoadPage() {
        InitValue();
        InitCanvas();
        OnDraw();
        setInterval(OnDraw, 50);
    }

    window.onload = onLoadPage();
</script>
</body>
</html>

 

 


1. HTML로 구를 그리기 위한 기본적인 뼈대를 작성한다.

아래 코드에서 _drawSphere()를 채워 나갑니다.

하기 HTML 코드는 좋은 예제가 아닙니다. HTML 관련은 인터넷에 있는 좋은 코드를 참고 하시기 바랍니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sphere</title>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        canvas {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
<div align='center'>
    <canvas id="canvas"></canvas>
</div>
<script language="JavaScript">
    let cvs;
    let canvas;
    let bufCanvas;
    let bufCtx;

    function InitCanvas() {
        height = window.innerHeight;
        width = window.innerWidth;

        console.log(">Width:", width);
        console.log(">Heigth:", height);

        canvas = document.getElementById("canvas");
        canvas.width = width;
        canvas.height = height;
        cvs = canvas.getContext("2d");

        bufCanvas = document.createElement("canvas");
        bufCanvas.width = canvas.width;
        bufCanvas.height = canvas.height;
        bufCtx = bufCanvas.getContext("2d");
    }

    function _drawSphere() {

    }

    function OnDraw() {
        let startTime = new Date();

        bufCtx.strokeStyle = "black";
        bufCtx.fillStyle = "black";
        bufCtx.fillRect(0, 0, canvas.width, canvas.height);

        _drawSphere();

        cvs.clearRect(0, 0, canvas.width, canvas.height);
        cvs.drawImage(bufCanvas, 0, 0);
        console.log("Elapsed time: " + (new Date() - startTime));
    }


    function onLoadPage() {
        InitCanvas();
        OnDraw();
        setInterval(OnDraw, 50);
    }

    window.onload = onLoadPage();
</script>
</body>
</html>

 

2. 원 그리기

원점을 기준으로 지름 r인 원은 아래 수식으로 표현 할 수 있습니다.

이때, x, y는 아래와 같이 구 할 수 있습니다.


원래 작성한 코드는 아래와 같다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sphere</title>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        canvas {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
<div align='center'>
    <canvas id="canvas"></canvas>
</div>
<script language="JavaScript">
    // Start: 2022.01.16
    // Update: 2022.01.18

    let cvs;
    let canvas;
    let bufCanvas;
    let bufCtx;
    let thetaX = 0;
    let thetaZ = 0;

    function InitCanvas() {
        height = window.innerHeight;
        width = window.innerWidth;

        console.log(">Width:", width);
        console.log(">Heigth:", height);

        canvas = document.getElementById("canvas");
        canvas.width = width;
        canvas.height = height;
        cvs = canvas.getContext("2d");

        bufCanvas = document.createElement("canvas");
        bufCanvas.width = canvas.width;
        bufCanvas.height = canvas.height;
        bufCtx = bufCanvas.getContext("2d");
    }

    function drawCircle(x, y, c, r) {

        bufCtx.beginPath();
        bufCtx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
        bufCtx.strokeStyle = "rgb(255, 255, 255)";
        bufCtx.arc(x, y, r, 0, Math.PI * 2);
        bufCtx.stroke();
        bufCtx.fill();
        bufCtx.closePath();
    }

    function _draw() {
        let maxSize = canvas.height < canvas.width ? canvas.height : canvas.width;
        let dimen = 8;
        let ox = canvas.width / 2;
        let oy = canvas.height / 2;
        let R1 = maxSize/20;  // 원의 반지름

        // 카메라와 스크린의 거리를 z'라 하고, 그 투영되는 상을 x',y'
        // z:x = z':x'
        // z:y = z':y'
        // x' = xz'/z, y' = yz'/z
        // z' = z1
        // x', y' = xz1/z, yz1/z
        // z의 최대거리 z2 = 1000이라 하면
        // x' <= (height/2 * 0.8) (화면 중앙 위치, 마진 0.1)
        // x 의 최대 값은 R1 + R2
        // x' = Z1(R1+R2)/z2 = height * 0.4
        // Z1 = Z2 * height * 0.4 / (R1+R2)

        let ZZ2 = 1000;
        let ZZ1 = maxSize * ZZ2 * 0.4 / R1;

        let points = [];

        for (let i = 0; i < 628; i += dimen) {
            let x1 = Math.cos(i/100) * R1;
            let y1 = Math.sin(i/100) * R1;
            let nx1 = Math.cos(i/100);
            let ny1 = Math.sin(i/100);

            for (let j = 0; j < 628; j += dimen) {
                // Y축 회전
                let x2 = x1 * Math.cos(j/100);
                let y2 = y1;
                let z2 = x1 * Math.sin(j/100);

                let nx2 = nx1 * Math.cos(j/100);
                let ny2 = ny1;
                let nz2 = nx1 * Math.sin(j/100);

                // X축 회전
                let x3 = x2;
                let y3 = y2 * Math.cos(thetaX/100) - z2 * Math.sin(thetaX/100);
                let z3 = y2 * Math.sin(thetaX/100) + z2 * Math.cos(thetaX/100);

                let nx3 = nx2;
                let ny3 = ny2 * Math.cos(thetaX/100) - nz2 * Math.sin(thetaX/100);
                let nz3 = ny2 * Math.sin(thetaX/100) + nz2 * Math.cos(thetaX/100);

                // Z축 회전
                let x4 = x3 * Math.cos(thetaZ/100) - y3 * Math.sin(thetaZ/100);
                let y4 = x3 * Math.sin(thetaZ/100) + y3 * Math.cos(thetaZ/100);
                let z4 = ZZ2 + z3;

                let nx4 = nx3 * Math.cos(thetaZ/100) - ny3 * Math.sin(thetaZ/100);
                let ny4 = nx3 * Math.sin(thetaZ/100) + ny3 * Math.cos(thetaZ/100);
                let nz4 = nz3;

                // 법선 벡터 (nx4, ny4, nz)와 광원의 백터 내적 계산
                // 광원 위치는 (0, 0, -1)
                let lx = 0;
                let ly = 0;
                let lz = -1;
                let light = nx4 * lx + ny4 * ly + nz4 * lz;

                if (light > 0) {
                    let color = Math.round(light * 255);
                    
                    // x' = xz'/z, y' = yz'/z
                    let xp = Math.floor(x4 * ZZ1 / z4);
                    let yp = Math.floor(-y4 * ZZ1 / z4);

                    points.push([xp + ox, yp + oy, 255-color]);
                }
            }
        }

        bufCtx.strokeStyle = "black";
        bufCtx.fillStyle = "black";
        bufCtx.fillRect(0, 0, canvas.width, canvas.height);
        points.forEach(e => drawCircle(e[0], e[1], e[2], 1));

        thetaX = (thetaX + 2) % 629;
        thetaZ = (thetaZ + 2) % 629;
    }

    function OnDraw() {
        _draw();

        cvs.clearRect(0, 0, canvas.width, canvas.height);
        cvs.drawImage(bufCanvas, 0, 0);
    }


    function onLoadPage() {
        InitCanvas();
        OnDraw();
        setInterval(OnDraw, 50);
    }

    window.onload = onLoadPage();
</script>
</body>
</html>
Posted by chobocho
My Life/version 22 (2022)2021. 12. 14. 22:14

청소의 귀차니즘으로 인하여, 비스포크 제트 봇을 구매 후 기록한 내돈내산 사용기 입니다.

구매이유

  • 라이다 장착
  • 스마트싱스 연동
  • 지도 표시 기능

박스 개봉기

박스를 열면 아래와 같이 이쁜 녀석이 나온다.

청소하기

    • 아래와 같이 이쁘게 지도를 그려준다

 

    • 케이블을 잘 치워두지 않으면 케이블이 빨려 들어가서, 사고가 발생한다. (우측 하단하얀 부분)

 

  • 스마트싱즈 앱에서 제한구역(빨간 박스)를 설정하면 불상사를 막을 수 있다.



Posted by chobocho
Coding/Java 삽질기2021. 10. 24. 18:08

TextView에서 한 줄에 표시되는 글자수를 계산 하는 코드

var textView: TextView = findViewById(R.id.textView)
val COL : Int = Math.round(textView.width / textView.paint.measureText("가나다라마.") * 6)

그런데 OnCreate에서 위 함수를 사용하면 0이 나온다.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.textviewer)
      
        val vto: ViewTreeObserver = textView.getViewTreeObserver()
        vto.addOnGlobalLayoutListener {

            if (getWidthCount < 1) {
                getWidthCount++

                val COL : Int = Math.round(textView.width / textView.paint.measureText("가나다라마.") * 6)
                Log.i(TAG, "getWidth:" + COL)
            }
        }
    }

이 경우 위와 같이, 코드를 추가해 주면 된다.

Posted by chobocho
Coding/Java 삽질기2021. 10. 17. 13:38

Unit test에서 Test sample 파일을 읽어서 테스트 하는 방법

1. test 폴더에 resources 폴더를 만들고 테스트 파일을 넣는다

2. 아래와 같이 코드를 작성한다.

    @Test
    public void encrypt() throws URISyntaxException {
        File file = new File(getClass().getResource("/1.txt").toURI());
        assert(file != null);
        URL unavailableURL = getClass().getResource("/unavilable.txt");
        assert(unavailableURL == null);
    }

Posted by chobocho
Coding/JavsScript 삽질기2021. 10. 16. 13:54
Coding/Tip2021. 10. 16. 13:52

오늘날짜 입력: Ctrl + ;

'Coding > Tip' 카테고리의 다른 글

[DOSBOX] 창 크기 조절 방법  (0) 2023.01.27
[Android studio] 사용 팁  (0) 2020.04.13
사무직을 위한 Git 활용 법  (0) 2018.10.27
Posted by chobocho
My Life/version 6.12021. 9. 1. 00:01

프로그래밍 중급(?) 수준에 이르기 위해서 보면 좋을 책을 내 마음 대로 정리해 보았습니다.

재미로 읽어보시길 바랍니다.

좋은 책 있으시면 추천 부탁드립니다.

Clean architecture
Clean code
Clean coder
Clean software
CODE
Code craft
Code complete 2
Effective java 3/e
GoF의 디자인 패턴 
Head First Design Pattern 2/e
Refactoring 2/e
개발자의 글쓰기
김도형의 데이터 사이언스 스쿨 수학 편
맨먼스 미신
밑바닥부터 만드는 컴퓨팅 시스템
생각하는 프로그래밍
소프트웨어 장인
실용주의 프로그래밍
조엘 온 소프트웨어 
컴파일러 구조와 원리 - 컴파일러로 배우는 언어 처리 시스템
테스트 주도 개발
프로그래머의 길, 멘토에게 묻다
피플웨어 
한 권으로 읽는 컴퓨터 구조와 프로그래밍
해커와 화가
핸즈온 머신러닝
헤커의 기쁨 2/e


Posted by chobocho
Tip/Windows2021. 8. 9. 02:30

* 스캔스냅 으로 대량 자료 스캔시, 자동 회전이나 빈 페이지 삭제 기능이, 오히려 불편함을 초래 할 때가 있다.

해당 기능을 off 하려면 아래와 같다

'Tip > Windows' 카테고리의 다른 글

[C#] PictureBox 로 간단한 이미지 뷰어 만들기  (0) 2023.09.22
[Excel] 엑셀 수식 자동 계산이 안 될 때  (0) 2021.08.07
검색 잘 하기  (0) 2021.08.07
Posted by chobocho
Tip/Windows2021. 8. 7. 00:35

파일 > 옵션 > 수식에서 아래와 같이 

통합 문서 계산 > 자동  을 선택하며 된다.

'Tip > Windows' 카테고리의 다른 글

[ScanSnap] 스캔스냅 사용팁  (0) 2021.08.09
검색 잘 하기  (0) 2021.08.07
Xbox 4세대 컨트롤러 사용기  (0) 2021.04.15
Posted by chobocho
Tip/Windows2021. 8. 7. 00:31

1. 검색은 구글에서 하는 이다.

 

2. 핵심 검색어를 포함해라.

* 반드시 문장으로 써야 할 필요는 없다. 핵심 키워드만 나열해도 된다.

3. 특정 site 자료만 검색하는 방법

* 검색어 site:주소   와 같이 써주면 된다.

4. 내가 찾는 단어들이 반드시 포함된 사이트만 검색하기

  • 검색어 사이에 '+' 써주면 된다.
  • 예: 안드로이드, 테트리스, 만들기 3 단어가 반드시 포함된 사이트를 찾기

'Tip > Windows' 카테고리의 다른 글

[Excel] 엑셀 수식 자동 계산이 안 될 때  (0) 2021.08.07
Xbox 4세대 컨트롤러 사용기  (0) 2021.04.15
Batch file 템플릿  (2) 2020.12.22
Posted by chobocho