소프트웨어, 수학 자료 정리

'웹'에 해당되는 글 27건

  1. 마인드 맵 메뉴 분석
  2. CSS 와 자바 스크립트 연결
  3. 퍼즐 게임 분석
  4. 그림 위에 텍스트, 그림 덧붙이기 overlay text, image over image
  5. 가로, 세로 tab 메뉴 비교
  6. 자바스크립트 테트리스 코드 분석
  7. 자바스크립트 테트리스 코드 분석
  8. mathjax 예제
  9. 티스토리에 자바스크립트 MathJax 사용하기, 수학식 표시하기
  10. 자바스크립트 원통 그리기
  11. 자바스크립트 캔버스 에니메이션 시소
  12. 자바스크립트 캔버스 (에니메이션) 펜둘럼(Pendulumn)
  13. 자바스크립트 캔버스를 이용하여 사인파 그리기
  14. 자바스크립트 instanceof 연산자
  15. 자바스크립트 캔버스 원 그리기 arc()
  16. 자바스크립트 팩맨 Pacman 소스코드 알고리즘 분석
  17. 자바스크립트 math.random()
  18. (스크랩)자바스크립트 뱀게임(스네이크) 소스코드 알고리즘 분석
  19. (스크랩)자바스크립트 벽돌깨기 소스 코드 알고리즘 분석
  20. 자바스크립트 HTML 캔버스 drawImage() 메소드
  21. 자바스크립트 인베이더 소스코드 알고리즘 분석
  22. 자바스크립트 배열 push() pop() shift() unshift() splice()
  23. 자바 스크립트 테트리스 소스코드 알고리즘 분석
  24. 자바스크립트 원 모양의 사인파를 캔버스로 그리기
  25. (스크랩) 자바스크립트 마우스 선 그리기
  26. HTML 웹사이트 만들 때 필요한 지식
  27. 목차

마인드 맵 메뉴 분석

https://codepen.io/j4k0bkg/pen/PdzRrr

 

MindMap

...

codepen.io

 

tag 해석

<html>

<jquery>

>unbind

https://www.w3schools.com/jquery/event_unbind.asp

 

jQuery unbind() Method

jQuery unbind() Method ❮ jQuery Event Methods Example Remove all event handlers for all

elements: $("button").click(function(){   $("p").unbind(); }); Try it Yourself » Definition and Usage The unbind() method was deprecated in version 3.0. Use the off

www.w3schools.com

>attr

https://www.w3schools.com/jquery/html_attr.asp

 

jQuery attr() Method

jQuery attr() Method ❮ jQuery HTML/CSS Methods Example Set the width attribute of an image: $("button").click(function(){   $("img").attr("width","500"); }); Try it Yourself » Definition and Usage The attr() method sets or returns attributes and values of

www.w3schools.com

>after

https://www.w3schools.com/jquery/html_after.asp

 

jQuery after() Method

jQuery after() Method ❮ jQuery HTML/CSS Methods Example Insert content after each

element: $("button").click(function(){   $("p").after("

Hello world!

"); }); Try it Yourself » Definition and Usage The after() method inserts specified content afte

 

www.w3schools.com

 

 

https://codepen.io/Taxnot/pen/RNdzmY

 

mindmap

...

codepen.io

해석

 

CSS 와 자바 스크립트 연결

마우스 클릭  작동법

 

출처: 

https://codepen.io/hoojacks/pen/voBbgx

 

auto-generate border radius

...

codepen.io

 

퍼즐 게임 분석

https://codepen.io/Hassani/pen/ApmJf

그림 위에 텍스트, 그림 덧붙이기 overlay text, image over image

https://codepen.io/vincentntang/pen/LKgWbv

 

Ecommerce Desk Configurator

I was shopping for a new standing desk and stumbled upon this cool site: https://www.fully.com/standing-desks/jarvis/jarvis-adjustable-height-desk-bamb...

codepen.io

http://codeshorts.com/JavaScript-Draw-Image-to-Canvas-HTML5-and-overlay-text

 

JavaScript Draw Image to Canvas HTML5 and overlay text | CodeShorts.com

JS and HTML5 code to draw a jpeg and overlay the jpeg with text. Allowing visitors to save

codeshorts.com

https://www.w3schools.com/howto/howto_css_image_text_blocks.asp

'' 카테고리의 다른 글

CSS 와 자바 스크립트 연결  (0) 2019.07.22
퍼즐 게임 분석  (0) 2019.07.11
가로, 세로 tab 메뉴 비교  (0) 2019.07.10
자바스크립트 테트리스 코드 분석  (0) 2019.03.16
자바스크립트 테트리스 코드 분석  (0) 2019.03.12

가로, 세로 tab 메뉴 비교

<!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}-->

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_tabs https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_vertical_tabs
<style> <style>
  * {box-sizing: border-box}
/* Style the tab */ /* Style the tab */
.tab { .tab {
overflow: hidden;  
  float: left;
border: 1px solid #ccc; border: 1px solid #ccc;
background-color: #f1f1f1; background-color: #f1f1f1;
  width: 30%;
  height: 300px;
} }
/* Style the buttons inside the tab */ /* Style the buttons inside the tab */
.tab button { .tab button {
  display: block;
background-color: inherit; background-color: inherit;
float: left;  
  color: black;
padding: 14px 16px; padding: 22px 16px;
  width: 100%;
border: none; border: none;
outline: none; outline: none;
  text-align: left;
cursor: pointer; cursor: pointer;
transition: 0.3s; transition: 0.3s;
font-size: 17px; font-size: 17px;
} }
/* Change background color of buttons on hover */ /* Change background color of buttons on hover */
.tab button:hover { .tab button:hover {
background-color: #ddd; background-color: #ddd;
} }
/* Create an active/current tablink class */ /* Create an active/current "tab button" class */
.tab button.active { .tab button.active {
background-color: #ccc; background-color: #ccc;
} }
/* Style the tab content */ /* Style the tab content */
.tabcontent { .tabcontent {
display: none;  
  float: left;
padding: 6px 12px; padding: 0px 12px;
border: 1px solid #ccc; border: 1px solid #ccc;
border-top: none;  
  border-left: none;
  width: 70%;
  height: 300px;
} }
</style> </style>
<script> <script>
function openCity(evt, cityName) { function openCity(evt, cityName) {
var i, tabcontent, tablinks; var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent"); tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) { for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none"; tabcontent[i].style.display = "none";
} }
tablinks = document.getElementsByClassName("tablinks"); tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) { for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", ""); tablinks[i].className = tablinks[i].className.replace(" active", "");
} }
document.getElementById(cityName).style.display = "block"; document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active"; evt.currentTarget.className += " active";
} }
</script> </script>

 

자바스크립트 테트리스 코드 분석

출처: https://codepen.io/kudchikarsk/pen/GYKmdd

 

<HTML>Pug

3: 배너

7: 블록 그리기 

8: 블록 160개

 

<CSS>

# : id

.  : class

111: color picker

117: opacity // 투명도 조정

 

<JavaScript>

1: Position class

8: Block class

더보기

   21: init()

   25: render()

   32: fall()

   52: getPosition

   62: destroy()

        63: $().remove() // HTML에서 ()요소 제거 

   88: fallingPosiotions()

        90: .map (52)

67: Shape class

더보기

    72: getBlocks()

    76: init()

         78: block.init 21

    82: 

         84: 25

    94: fall()

         96: 32

    114: 40

142: Square class

153: LShape

     160: super // 부모 클래스와 연동하기 위해 사용한다.

     164: rotate()

     171: rotatePosition()

389: Board class

더보기

     396: parseInt() // 정수로 변환

     401: setScore()

     406: getScore()

     410: init()

             411: $().each // 바탕화면 블록 그리기를 반복한다. 

            412: parseInt()

            

            

     426: newGame()

           427: this.shapes // 606 에서 배열 값 만듬

428: 614

429: 618 (72)

432: 62

436:  441

     441: initGameLoop()

              447: 451

     451: gameLoop()

     452: 483 // shape 그리기, 충돌검사

     453: 509 // 블록 그리기, 채움 검사, 채움지우기

     454: 572 // 새 shape 생성

     455: 460 // 게임 끝나면 다시 그리기

     460: gameUpdate()

           464: clearinterval() // setinterval 작동 해제

     473: isGameOver()

     483: renderShapes()

            484: 610

            486: 624 (88) // 벽 검사

            487: 633 // 블록 유무 검사

            489: 94 

            490: 82

     502: dropShape

     509: renderBlocks()

     531: flashBlocks()

     539: fallBlocks()

     551: removeBlocks()

     557: destroyBlocks()

     563: getBlock()

     572: spawnShapes() // Shape 생성

           576: 689

           604: shape.init 76 

 

     610: getShape()

     614: removeShape()

           615: .splice ( indexof )

     618: addBlocks() // 블록 생성

     624: arePositionWithinBoard()

     633: areBlockEmpty()

     645: leftKeyPress()

           651: 114

           652: shape.render() // 옆으로 이동 그리기

     657: rotate()

     669: rightKeyPress()

     689: getRandomRange() // 난수 생성, 블록 선택

 

 


1. 보드 그리기 : <Html>pug <CSS> 

2. 블록 생성 : 

   메모리 생성 : 572

   화면 생성    

3. 블록 가로 이동 : 

   좌표 변경: 114

   화면 표시

4. 블록 회전 : 

   좌표 변경 : 171

   화면 표시

5. 블록 낙하 :

    좌표 값 변경 : shape.fall()

    화면 표시: shape.render()

6. 블록 충돌 검사 벽 : 624

7. 블록 충돌 검사 블록 : 633

8. 블록 채워지면 지우기 : renderBlocks()

   메모리 값 삭제 destroyBlocks(), removeBlocks()

   메모리 값 이동 fallBlocks

   화면 삭제

9. 점수 계산

 


 

 

 

자바스크립트 테트리스 코드 분석

출처: https://codepen.io/iftrrtrn/pen/EKwJLo

 

<CSS>

 

6: dispaly: inline-block;

 

   div 배치할 때 float: ; 보다 간단하다.

 

22: border-collapse: collapse; //table과 td 사이의 테두리를 없앱니다.

 

27: first-child // 첫번째를 선택하는 것

 

<javascript>

 

7: tetris class

9:   ~~

19: TetraminoForms

55: fieldArray

64: generateComponent() 

    //클로저 함수 

   // 미리보기, 게임판, 게임판 배열 만들기

66: 미리보기 그리기

75: appendChild // td 같은 것 추가

81: classLIst.add // class 추가

92: piece 없는 보드 그리기

114: 보드 배열 값 초기화

      filedArray.push([])

      filedArray[i].push('.')

      (0, 0) (0, 1) (0, 2) ..... (0, 9)

      (1,0)   ....

      (2.0)  

      .

      .

128: Tetramino class

130: Tetramino 클래스

      this.coords  : 최초 생성 좌표

 

136: Tetramino 회전 함수

      form 배열 좌표 : 적색은 회전하는 좌표

      (0,0) (0,1) (0,2) (0,3) (0,4)

      (1,0) (1,1) (1,2) (1,3) (1,4)

      (2,0) (2,1) (2,2) (2,3) (2,4)

      (3,0) (3,1) (3,2) (3,3) (3,4)

      예제 

      TetraminoForms = [

       [

        [ 'i', 'i', 'i', 'i' ]

       ],

       를 선택했을 경우 

      temp.length = 4

      temp[0].length = 1

      form.length = 1

      form[0].length = 4

 

146: 회전 시 블록 충돌 확인

163: if (coords[0] === 0 && coords[1] === -1) // ↑ 키가 눌러졌다면

168: 좌우벽(폭) 충돌 검사

169: filedArray[0].length = 1

172: 좌우 값 더함

176: 하강 검사, 

177: filedArray.length = 7

178: 하강 좌표 증가 

 

184: 보드 그리기

       fieldArray.length = 20

       filedArray[0].length = 10

193: drawNextTetramino

207: 키 입력 

                      [0, -1] 38 

       37 [-1, 0]               [1, 0] 39 

                       [0, 1] 40 

216: runTetris()

// tetramino 생성

226: moveTetramino() // 자동으로 떨어지기

         233: 전단계 piece 지우기 위해서 보드 배열 값 세팅

243: piece 떨어지는 것(이동) 그리기, 블록 배열 값 세팅

248: 입력이 없다로 세팅

257: fallTetramino()

267: 바닥 충돌 검사

277: 블록 충돌 검사

287: side 충돌 검사

 

315: 채움 검사

339: 맨 위에 검사

345: resetGame()

 

356: 최초 시작

 

더보기

356

357

358

359 : 216

220 : 193

222: 226

 

 

 

 

 

 

mathjax 예제

$$\begin{align} (x+1)^2 &\cssId{Step1}{= (x+1)(x+1)}\\ &\cssId{Step2}{= x(x+1) + 1(x+1)}\\ &\cssId{Step3}{= (x^2+x) + (x+1)}\\ &\cssId{Step4}{= x^2 + (x + x) + 1}\\ &\cssId{Step5}{= x^2+2x+1}\\ \end{align}$$





티스토리에 자바스크립트 MathJax 사용하기, 수학식 표시하기

아래 소스 코드를 HTML 입력 창에서 입력한다.


예제 소스 코드


<script type="text/x-mathjax-config">

  MathJax.Hub.Config({

    tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}

  });

</script>

<script type="text/javascript"

   src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">

</script>


<p>

When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are

$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}. \tag{1}$$

</p>


실행 결과 화면


When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}. \tag{1}$$

$$\begin{align} (x+1)^2 &\cssId{Step1}{= (x+1)(x+1)}\\ &\cssId{Step2}{= x(x+1) + 1(x+1)}\\ &\cssId{Step3}{= (x^2+x) + (x+1)}\\ &\cssId{Step4}{= x^2 + (x + x) + 1}\\ &\cssId{Step5}{= x^2+2x+1}\\ \end{align}$$


출처

https://cdn.mathjax.org/mathjax/latest/test/examples.html


그래프, 사운드 소스코드

<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css">

<script type="text/javascript" src="http://www.charlie-roberts.com/gibberish/build/gibberish.js"></script>

<script type="text/javascript" src="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraphcore.js"></script>


<div id="jxgbox" class="jxgbox" style="width:400px; height:400px; border">

<script type="text/javascript">

 Gibberish.init();

 Gibberish.Time.export();

 Gibberish.Binops.export();


 var board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox:[-1,10,10,-10], axis:false});


 var sinewave = new Gibberish.Sine( 440, .25 ).connect();


 var slide = board.create('slider', [[2, 8], [8, 8], [100, 440, 1000]]);

 var sinecurve = board.create('functiongraph', [function(x) { return 5 * Math.sin((sinewave.frequency / 200.0) * 2* Math.PI * x); }]);


 board.on ('update', function() {

    sinewave.frequency = slide.Value();

 } );

</script>

</div>


결과


출처 : http://jsxgraph.uni-bayreuth.de/wiki/index.php/JSXGraph_and_sound


자바스크립트 원통 그리기

출처: https://stackoverflow.com/questions/14498521/how-to-draw-a-cylinder-on-html5-canvas



Your browser does not support the HTML5 canvas tag.

자바스크립트 캔버스 에니메이션 시소

참고 : https://www.w3schools.com/graphics/tryit.asp?filename=trygame_rotate_game

참고 : https://codepen.io/Anwesh43/pen/QpaVEV?editors=1010

 
 


소스 코드

<style>

canvas {

    border:1px solid #d3d3d3;

    background-color: #f1f1f1;

}

</style>


<canvas id="canvas" style="width: 480; height: 270"></canvas>


<button type="button" onclick="startGame()">Click Me!</button>


<script>


var myGamePiece;


function startGame() {

    myGamePiece = new component(50, 30, "red", 80, 75);

    myGameArea.start();

}


var myGameArea = {

    canvas : document.createElement("canvas"),

    start : function() {

        this.context = canvas.getContext("2d");

        this.interval = setInterval(updateGameArea, 200);

    },

    stop : function() {

        clearInterval(this.interval);

    },    

    clear : function() {

        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

    }

}


function component(width, height, color, x, y) {

    this.width = width;

    this.height = height;

    this.angle = 0;

    this.x = x;

    this.y = y;

    this.deg = 0;

    this.dir = 1;

    this.update = function() {

        ctx = myGameArea.context;

        ctx.save();

        ctx.translate(this.x, this.y);        

        ctx.rotate(this.angle);

        ctx.fillStyle = color;

        ctx.fillRect(0, -this.height , this.width, this.height);

  //대칭으로 그리기

        ctx.scale(-1,1)

        ctx.fillRect(0, -this.height , this.width, this.height);       

        ctx.restore();    

    }

}


function updateGameArea() {


    myGameArea.clear();

    myGamePiece.deg += myGamePiece.dir*6

    if (myGamePiece.deg >=30) {

    myGamePiece.dir = -1

    }

if (myGamePiece.deg <=-30) {

    myGamePiece.dir = 1

    }

    

    myGamePiece.angle = myGamePiece.deg * Math.PI / 180;    

    myGamePiece.update();

}


</script>



자바스크립트 캔버스 (에니메이션) 펜둘럼(Pendulumn)

참고 : https://www.w3schools.com/graphics/tryit.asp?filename=trygame_rotate_game

참고 : https://codepen.io/Anwesh43/pen/QpaVEV?editors=1010

 
 


소스 코드

<style>

canvas {

    border:1px solid #d3d3d3;

    background-color: #f1f1f1;

}

</style>


<canvas id="canvas" style="width: 480; height: 270"></canvas>


<button type="button" onclick="startGame()">Click Me!</button>


<script>


var myGamePiece;


function startGame() {

    myGamePiece = new component(30, 30, "red", 80, 75);

    myGameArea.start();

}


var myGameArea = {

    canvas : document.createElement("canvas"),

    start : function() {

        this.context = canvas.getContext("2d");

        this.interval = setInterval(updateGameArea, 200);

    },

    stop : function() {

        clearInterval(this.interval);

    },    

    clear : function() {

        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

    }

}


function component(width, height, color, x, y) {

    this.width = width;

    this.height = height;

    this.angle = 0;

    this.x = x;

    this.y = y;

    this.deg = 0;

    this.dir = 1;

    this.update = function() {

        ctx = myGameArea.context;

        ctx.save();

        ctx.translate(this.x, this.y);        

        ctx.rotate(this.angle);

        ctx.fillStyle = color;

        ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);        

        ctx.restore();    

    }

}


function updateGameArea() {


    myGameArea.clear();

    myGamePiece.deg += myGamePiece.dir*6

    if (myGamePiece.deg >=30) {

    myGamePiece.dir = -1

    }

if (myGamePiece.deg <=-30) {

    myGamePiece.dir = 1

    }

    

    myGamePiece.angle += myGamePiece.deg * Math.PI / 180;    

    myGamePiece.update();

}


</script>



자바스크립트 캔버스를 이용하여 사인파 그리기

소스 코드

<canvas id="myCanvas" width="360" height="400" style="border:1px solid #d3d3d3;">

Your browser does not support the canvas element.

</canvas>


<script>


var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");


// X축 그리기

for(x=0; x<360; x += 20){

    ctx.moveTo(x+5,180);

    ctx.lineTo(x,180);

}


// 청색 사인파 그리기

ctx.moveTo(0,180);

ctx.strokeStyle="blue";

for(x=0; x<=360; x+=1){

    y = 180.0 - Math.sin(x*Math.PI/180)*120;

    ctx.lineTo(x,y);

}

ctx.stroke();


// 적색 사인파 그리기

ctx.beginPath();

ctx.moveTo(0,180);

ctx.strokeStyle="red";

for(x=0; x<=360; x+=1){

    y = 180.0 - Math.sin(2*x*Math.PI/180)*120;

    ctx.lineTo(x,y);

}



ctx.stroke();


</script>



<실행결과>

Your browser does not support the canvas element.



참고: https://stackoverflow.com/questions/29917446/drawing-sine-wave-in-canvas

자바스크립트 instanceof 연산자

<설명>


instanceof 연산자는 지정된 객체가  지정된 객체의 인스턴스 인 경우 true를 반환합니다.


<예제>


var colors = { "white", "black"};


colors instanceof Array;

colors instanceof Number;


<결과>



자바스크립트 캔버스 원 그리기 arc()

출처: https://www.w3schools.com/tags/canvas_arc.asp


원을 그린다.

arc( centerX, centerY, Radius, StartAngle, EndAngle)

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">

Your browser does not support the HTML5 canvas tag.</canvas>


<script>


var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");

ctx.beginPath();

ctx.arc(100, 75, 50, 0,  2* Math.PI);

ctx.stroke();


</script> 

Your browser does not support the HTML5 canvas tag.


<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">

Your browser does not support the HTML5 canvas tag.</canvas>


<script>


var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");

ctx.beginPath();

ctx.arc(100, 75, 50, 0,  1.5* Math.PI);

ctx.stroke();


</script> 


Your browser does not support the HTML5 canvas tag.


자바스크립트 팩맨 Pacman 소스코드 알고리즘 분석

출처: http://www.masswerk.at/JavaPac/pacman-howto.html

 

참고: https://codepen.io/hellokatili/pen/xwKRmo

 

object

  1. Pacman.Ghost : 26
  2. Pacman.User   : 279
  3. Pacman.Map   : 532
  4. PACMAN        : 773
  5. KEY               : 1099

constant

    Pacman.WALL : 1120

    Pacman.BISCUIT

    Pacman.EMPTY

    Pacman.BLOCK

    Pacman.PILL

    Pacman.MAP      : 1126

    Pacman.WALLS   :  1151       

method
  • Pacman.Ghost
draw
  • Pacman.User
draw
drawDead
방향전환
keyDown
getNewCoord
좌표변환, 충돌검사, 알약 존재유무 설정
isOnSamePlane
move
입모양
calcAngle
  • Pacman.Map
drawWall
drawPills
drawBlock
  • PACMAN

 

충돌검사
collided
 startNewGame : 826
키입력
      keyDown : 835

 

      map.draw : 
      startLevel : 816
 mainDraw : 913

        

        init :  1030

              loaded : 1082

              mainLoop      : 956      

 setInterval (mainLoop,) : 1089

 

global NONE      
  UP      
  LEFT      
  DOWN      
  RIGHT      
  WAITING      
  PAUSE      
  PALYING      
  COUNTDOWN      
  EATEN_PAUSE      
  DYING      
  Pacman      
         
object Pacman.Ghost Pacman.User Pacman.Map PACMAN
         
variable position position height state
  direction direction width audio
  eatable   blockSize ghosts
  eaten eaten pillSize ghostSpecs
  due due map eatenCount
    lives   level
    scrore   tick
    keyMap   ghostPos
        userPos
        stateChanged
        timerStart
        lastTime
        ctx
        timer 
        map
        user 
        stored
         
method   addScore withinBounds getTick
  addBounded theScore isWall  
    loseLife   dialog
  isDangerous getLives isFloorSpace soundDisabled
  isVunerable initUser   startLevel
  isHidden newLevel    
  getNewCoord getNewCoord   startNewGame
  getRandomDirection keyDown   keyDown
        keyPress
        loseLife
  reset reset reset setState
  oppositeDirection resetPosition block collided
      setBlock  
  makeEatable      
         
        mainLoop
    next    compltedLevel
  nextSquare nextSquare   eatenPill
  onGridSquare onGridSquare    
  onWholeSquare onWholeSquare    
    isMidSquare    
  pointToCoord pointToCoord    
    isOnSamePlane   init
  secondsAgo     load
  pane     loaded
  move move   setInterval
  getColour      
    calcAngle    
  eat      
  draw draw  draw mainDraw
    drawDead drawBlock drawScore
      drawWall drawFooter
      drawPills redrawBlock

 

https://mind42.com/public/cb6576b6-9983-43ce-ad03-56a57c1feaf7

불러오는 중입니다...

 

자바스크립트 math.random()

math.random()

기능

0과 1사이의 난수 발생기



(스크랩)자바스크립트 뱀게임(스네이크) 소스코드 알고리즘 분석

출처: http://thecodeplayer.com/walkthrough/html5-game-tutorial-make-a-snake-game-using-html5-canvas-jquery


목록

그리기

    • 뱀 (snake) 
      • 최초 5개 그리기: 배열 5개추가 snake_array.push() 
      • 이동 : 좌표 값을 바꾼다. 머리의 좌표 값을 바꾼다. 꼬리의 좌표 값을 삭제(snake_array.pop())
      • 방향 전환 : 좌표 값을 바꾼다. 꼬리 삭제snake_array.pop()
      • 꼬리 증가 : 배열 첫번째에 값을 하나를 추가한다. snake_array.unshift()
    • 먹이 (food)
      • 난수 발생 : math.random(), math.round()
      • 그리기

반복 작동 : setInterval()

충돌검사 : 좌표 비교

키입력 : $(document).keydown(function(e){

var key = e.which;

배열 : snake_array

최초 배열  머리좌표                    꼬리좌표

               (4, 0) (3, 0) (2, 0) (1, 0) (0, 0)



출처: http://jsxgraph.uni-bayreuth.de/wiki/index.php/Snake_-_the_game

(스크랩)자바스크립트 벽돌깨기 소스 코드 알고리즘 분석

출처: https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript


-목록-

그리기

    • 벽돌 (Brick) : rect()를 활용하여 그린다.
    • 공 (Ball) : arc()를 활용하여 그린다.
    • 채 (Paddle) : rect()를 활용하여 그린다.

반복 : requestAnimationFrame()

공 움직이기 : 지우고 좌표를 바꾸어 다시 그린다.

공 튀는 동작 : 대칭 수학 공식을 활용한다. 좌표를 바꾼다. 다시 그린다.

충돌 검사 : 좌표를 비교한다.

채 (Paddle) 움직이기 : 지우고 좌표를 바꾸어 다시 그린다.

마우스로 채 움직이기 : 마우스 이벤트를 활용한다. 좌표를 바꾼다. 지운다. 그린다.

키입력 : document.addEventListoner() 활용한다.

마우스 입력 : document.addEventListoner() 활용한다.

배열 bricks



자바스크립트 HTML 캔버스 drawImage() 메소드

구조

context.drawImage ( img, sourceX, sourceY, sourceWidth, sourceHight, x, y, Width, Hight )


설명

img : 사용할 이미지

sourceX : 이미지 안에서 x 좌표

sourceY : 이미지 안에서 y 좌표

sourceWidth : 사용할 폭

sourceHight : 사용할 높이

x : 캔버스 안에서 x 좌표

y : 캔버스 안에서 y 좌표

Width : 사용할 폭

Hight : 사용할 높이


예제

<p>사용한 이미지</p>

<img id="alien" width="240" height="277" src="https://github.com/gregquat/inbeda/raw/master/sprite.png" style="background-color: black">


<p>캔버스:</p>

<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;background-color:black">

Your browser does not support the HTML5 canvas tag.

</canvas>


<script>

window.onload = function() {

    var c = document.getElementById("myCanvas");

    var ctx = c.getContext("2d");

    var img = document.getElementById("alien");

    ctx.drawImage(img, 0,0,28,20,10, 10, 28, 20);

    ctx.drawImage(img, 0,0,28,20,40, 10, 28, 20);

    ctx.drawImage(img, 30,0,28,20,10, 28, 28, 20);


}

</script>

실행결과


사용한 이미지

The Scream

캔버스:

Your browser does not support the HTML5 canvas tag.

참고: https://www.w3schools.com/

자바스크립트 인베이더 소스코드 알고리즘 분석

출처: http://jsfiddle.net/ARTsinn/GgxjY/

참고사이트 : https://www.w3schools.com/


목록

그리기

    • Alien (적, 외계인) :  Alien.draw()
    • Gun (플레이어) :     Gun.draw()
    • ray (총알) :            Gun.ray.draw()
    • 폭파 :                   Alien.draw()

반복 작동 : setInterval()

충돌검사 (checkCollision) : Alien.checkCollision()

키입력 : Game.onkeydown(), Game.onkeyup()


<그리기 예제>

<p>사용한 이미지:</p>

<img id="alien" width="240" height="277" src="https://github.com/gregquat/inbeda/raw/master/sprite.png" alt="The Scream"style="background-color: black">


<p>Canvas:</p>

<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;background-color:black">

Your browser does not support the HTML5 canvas tag.

</Canvas>


<script>

window.onload = function() {

    var c = document.getElementById("myCanvas");

    var ctx = c.getContext("2d");

    var img = document.getElementById("alien");


    ctx.drawImage(img, 0,0,28,20,10, 10, 28, 20);

    

    ctx.drawImage(img, 28,0,28,20,10, 40, 28, 20);

    ctx.drawImage(img, 28,0,28,20,38, 40, 28, 20);

    

    ctx.drawImage(img, 56,0,28,20,10, 70, 28, 20);

    ctx.drawImage(img, 56,0,28,20,38, 70, 28, 20);

    ctx.drawImage(img, 56,0,28,20,66, 70, 28, 20);

// 메소드 설명: http://ilvjesus.tistory.com/1446

}

</script>

실행결과


사용한 이미지:

The Scream

캔버스:

Your browser does not support the HTML5 canvas tag.

<그리기 예제 2>

<canvas id="aliensCanvas" class="mesCanvas" width="530" height="600">Votre navigateur ne supporte pas les Canvas :(</canvas>



<script>

var Alien = function (aType, aLine, aCol) {

    this.type = aType;

    this.line = aLine;

    this.column = aCol;

    this.alive = true;

    this.height = 20;

    this.width = 28;

    this.positionX = 100 + this.width * this.column;

    this.positionY = 100 + 30 * this.line;

    this.state = 0;

    this.draw = function () { //draw the alien to his new position

        if (this.alive) { //draw the alien

            canvas.drawImage(

            pic,

            this.width * (this.type - 1),

            this.state,

            this.width,

            this.height,

            this.positionX,

            this.positionY,

            this.width,

            this.height);

        } 

    }

};

Game = {

    types: [1, 2, 2, 3, 3], //define kinds of aliens

    aliens: [

        [11],

        [11],

        [11],

        [11],

        [11]

    ],

    height: 0,

    width: 0,

    interval: 0,

    intervalDefault: 1000,

    init: function (aWidth, aHeight) { //initialize default position and behaviour

        for (i = 0; i < 5; i++) {

            for (j = 0; j < 11; j++) {

                this.aliens[i][j] = new Alien(this.types[i], i, j);

                this.alives++;

                this.aliens[i][j].draw();

            }

        }

        this.play();       

    },

    animate: function () { //move the aliens

        for (i = 0; i < 5; i++) {

            for (j = 0; j < 11; j++) {

                this.aliens[i][j].draw();

            }

        }     

    },

    play: function () { //play the game

        this.interval = this.intervalDefault;

        this.interval = this.interval - (this.level * 20);

        this.animation = setInterval("Game.animate()", this.interval);

    }


};


//define the global context of the game

var element = document.getElementById('aliensCanvas');

if (element.getContext) {

    var canvas = element.getContext('2d');

    var pic = new Image();

    pic.src = 'https://github.com/gregquat/inbeda/raw/master/sprite.png';

    Game.init(530, 500);

}

</script>

실행결과

Votre navigateur ne supporte pas les Canvas :(


Alien 

Gun

Game



자바스크립트 배열 push() pop() shift() unshift() splice()

var list= [ "A", "B", "C", "D"] 

list.length

배열에 할당 된 갯수를 센다.

var list= [ "A", "B", "C", "D"] 

list.push(1)


기능

배열에 끝에 값을 추가한다.



var list= [ "A", "B", "C", "D"] 

list.pop()


기능

배열 끝에 값을 삭제한다.



var list= [ "A", "B", "C", "D"] 

list.shift()


기능

배열의 첫번째 값을 삭제한다.




var list= [ "A", "B", "C", "D"] 

list.unshift(1)

배열 첫번째에 값을 추가한다.



 배열좌표

 배열 값



var list= [ "A", "B", "C", "D"] 

list.splice(2, 1, 1, 0)


기능

배열에 값을 추가한다.



 배열좌표

 배열 값


var list= [ A, B, C, D] 

list.splice(2, 1)


기능

배열 중간 부분 값을 삭제한다.




splice vs slice vs split

자바 스크립트 테트리스 소스코드 알고리즘 분석

출처http://codeincomplete.com/posts/javascript-tetris/


목차

블록 그리기

임의 블록 그리기

충돌 검사


블록 그리기 소스 코드

각 모양의 블록을 그려주는 소스 코드입니다.

실행결과

Your browser does not support the HTML5 canvas tag.


임의로(random) 선택해서 그려주기

실행결과

Your browser does not support the HTML5 canvas tag. 
 


충돌 검사


자바스크립트 원 모양의 사인파를 캔버스로 그리기

출처: https://stackoverflow.com/questions/33586669/agar-io-style-ripple-effect-for-canvas-arcs

출처: https://www.w3schools.com/howto/howto_js_rangeslider.asp


진폭:

파장 갯수:


Your browser does not support the HTML5 canvas tag.


소스코드

<input type="range" min="1" max="20" value="10" class="slider" id="amplitude">

  <p>진폭: <span id="demo"></span></p>


<input type="range" min="1" max="20" value="10" class="slider" id="count">

  <p>파장 갯수: <span id="demoCount"></span></p>


<p><br /></p><canvas id="canvas" width="300" height="300" style="border:1px solid #d3d3d3;">

Your browser does not support the HTML5 canvas tag.</canvas>


<script>

var slider = document.getElementById("amplitude");

var output = document.getElementById("demo");

output.innerHTML = slider.value;


slider.oninput = function() {

  output.innerHTML = this.value;

}


var sliderCount = document.getElementById("count");

var outputCount = document.getElementById("demoCount");

outputCount .innerHTML = sliderCount .value;


sliderCount .oninput = function() {

  outputCount .innerHTML = this.value;

}



function draw() {

 var canvas=document.getElementById("canvas");

 var ctx=canvas.getContext("2d");


 var cx=150;

 var cy=150;

 var radius=100;

 var amp=slider.value;

 var sineCount=sliderCount .value;

 ctx.clearRect(0,0,300,300);

 ctx.beginPath();

 for(var i=0;i<360;i++){

  var angle=i*Math.PI/180;

  var pt=sineCircleXYatAngle(cx,cy,radius,amp,angle,sineCount);

  ctx.lineTo(pt.x,pt.y);

 }

 ctx.closePath();

 ctx.stroke();

}


function sineCircleXYatAngle(cx,cy,radius,amplitude,angle,sineCount){

  var x = cx+(radius+amplitude*Math.sin(sineCount*angle))*Math.cos(angle);

  var y = cy+(radius+amplitude*Math.sin(sineCount*angle))*Math.sin(angle);

  return({x:x,y:y});

}

setInterval ( draw, 10);


</script>

(스크랩) 자바스크립트 마우스 선 그리기

출처

https://jsfiddle.net/richardcwc/d2gxjdva/

HTML 웹사이트 만들 때 필요한 지식

  • 인터넷 서버에 가입한다.

 
  • FTP 를 설치한다. 

HTML 화일을 서버에 보내기 위해서
 
  • w3school, mozilla 웹사이트를 참고하여 만든다.
 
  • 엑셀, 마인드맵을 활용하여 전체 흐름도를 만든다. 
 
 
(책) (사용자를)생각하게 하지마라
(책) 디자이너가 아닌 사람들을 위한 디자인북 : 배치, 정렬, 반복, 대비
ux 디자인 추천 서적
 
  • 통일성, 균형미가 느껴지게 만든다.
  • 수정하기 편하게 만든다.
  •  
  • 외부 파일 div 에 넣기 include another html in div in html file.

 

  • Layout, Grid 만들기
      보는 사람이 가장 쉽게 이해할 수 있는 레이아웃을 만든다.
      F 패턴
      Z 패턴
      3 등분
      황금 비율
(참고서적) 레이아웃 불변의 법칙
div 태그를 사용하여 만든다.

예제> 

      https://www.w3schools.com/w3css/w3css_templates.asp


아래 링크는 같은 높이 칼럼 만들 때 사용

https://www.w3schools.com/howto/howto_css_equal_height.asp

 반응형 웹 : 

     화면을 모니터 크기에 자동으로 맞춘다, 예를 들면 데스크탑, 스마트폰이다.

  • Menu 만들기

top navigation menu(tab)

dropdown menu

multi-level dropdown menu

tree menu예제: https://codepen.io/bisserof/pen/fdtBm

 tab menu

mind map: https://codepen.io/sblamey/pen/nBdeo

      target in div

      기능: 선택 된 메뉴에 표시 .active 활용한다.

  • 텍스트 

       < div style="text-align:justify"> 글자들을 직사각형 틀에 넣기

      Font 종류, 크기

     타이포 그래피 참고
 
website color schemes 활용할 것
3가지 정도의 색으로 구성할 것
 
  • 이미지

사진, 드로잉, 아이콘, 동영상 구도, 편집 등 법칙을 알고 만들것
큰 이미지를 사용할 것
이유 : 큰 것을 작게 만들 수 있기 때문이다.
 
  • style.css 를 이용할 것

이유: 
한번에 같은 내용들을 수정할 수 있다. 작업 시간을 줄인다.
예쁜 디자인을 만들수 있다.
 
  • 수학식, 차트 사용할 때

javascript 이용할 것
예제) 
 

 

 

Include another HTML file in a HTML file

I have 2 HTML files, suppose a.html and b.html. In a.html I want to include b.html. In JSF I can do it like that: It means that inside a.xhtml file, I can incl...

stackoverflow.com

 

Variation on Kenneth Kufluk's js-mindmap

This strength/force-based mind map script is based on Kenneth Kufluk's http://kenneth.kufluk.com/ 2010 version. I added size and color features....

codepen.io

 

Variation on Kenneth Kufluk's js-mindmap

This strength/force-based mind map script is based on Kenneth Kufluk's http://kenneth.kufluk.com/ 2010 version. I added size and color features....

codepen.io

 

Variation on Kenneth Kufluk's js-mindmap

This strength/force-based mind map script is based on Kenneth Kufluk's http://kenneth.kufluk.com/ 2010 version. I added size and color features....

codepen.io

 

Variation on Kenneth Kufluk's js-mindmap

This strength/force-based mind map script is based on Kenneth Kufluk's http://kenneth.kufluk.com/ 2010 version. I added size and color features....

codepen.io

 

Variation on Kenneth Kufluk's js-mindmap

This strength/force-based mind map script is based on Kenneth Kufluk's http://kenneth.kufluk.com/ 2010 version. I added size and color features....

codepen.io

 

Variation on Kenneth Kufluk's js-mindmap

This strength/force-based mind map script is based on Kenneth Kufluk's http://kenneth.kufluk.com/ 2010 version. I added size and color features....

codepen.io

 

 

목차


HTML 


CSS 


자바스크립트


배열

캔버스
그리기
에니메이션

게임