반응형
반응형

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

var d = new Date();
var n = d.getDay();

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

참고: 일요일은 0, 월요일은 1 등입니다.

var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

 

https://www.w3schools.com/js/js_date_methods.asp

 

JavaScript Get Date Methods

Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

 

 

반응형
반응형

자바스크립트 - 2차원 배열 선언 및 호출

//-- 알파벳 정렬 시작
//-- 배열 
var arr_cnt = $("#question_body .list-group-item-action").length;
var arr = new Array(arr_cnt);
for (var i = 0; i < arr_cnt; i++) {
    arr[i] = new Array(3);
    arr[i][0] = "";
    arr[i][1] = "";
    arr[i][2] = "";
}
//--- 내용 배열에 담기
$("#question_body .container-fluid .row div").children().each(function(i, elm) {
    arr[i][0] = $(this).text().toLowerCase();
    arr[i][1] = i;
    arr[i][2] = $(this).html();
});
arr.sort();
//-- 배열된 내용 html()
$("#question_body .container-fluid .row div").children().each(function(i, elm) {
    $(this).html(arr[i][2]) ;
});

//-- label for 맞추기
$('label').each(function(i, elm) {
  	$(this).attr('for',qid+'_'+(arr[i][1]+1));
});
//--  알파벳 정렬 종료
반응형
반응형

three.js

JavaScript 3D library

 

The aim of the project is to create an easy to use, lightweight, cross-browser, general purpose 3D library. The current builds only include a WebGL renderer but WebGPU (experimental), SVG and CSS3D renderers are also available in the examples.

 

  github.com/mrdoob/three.js/releases

 

Releases · mrdoob/three.js

JavaScript 3D library. Contribute to mrdoob/three.js development by creating an account on GitHub.

github.com

 

threejs.org/

 

Three.js – JavaScript 3D library

 

threejs.org

 

반응형
반응형

HTML5 Canvas: Lunch Wheel - javascript 룰렛

 

blog.bramp.net/post/2011/07/27/html5-canvas-lunch-wheel/

 

HTML5 Canvas: Lunch Wheel

In the on going battle to make my lunch time more optimised I decided to learn some Javascript, and how to use the HTML5 Canvas element. Turns out it’s not that hard, and I have now created Click to …

blog.bramp.net

 

blog.bramp.net/wheel/

 

Lunch Wheel

 

blog.bramp.net

<html><head>
<meta content="IE=EmulateIE7" http-equiv="X-UA-Compatible">
<title>Lunch Wheel</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.tinysort.min.js"></script>
<!--[if IE]><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jit/2.0.2/Extras/excanvas.min.js"></script><![endif]-->
<script type="text/javascript">
// Helpers
	shuffle = function(o) {
		for ( var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x)
			;
		return o;
	};

	String.prototype.hashCode = function(){
		// See http://www.cse.yorku.ca/~oz/hash.html		
		var hash = 5381;
		for (i = 0; i < this.length; i++) {
			char = this.charCodeAt(i);
			hash = ((hash<<5)+hash) + char;
			hash = hash & hash; // Convert to 32bit integer
		}
		return hash;
	}

	Number.prototype.mod = function(n) {
		return ((this%n)+n)%n;
	}
</script>
<script type="text/javascript">
venues = {
		"116208"  : "Jerry's Subs and Pizza",
		"66271"   : "Starbucks",
		"5518"    : "Ireland's Four Courts",
		"392360"  : "Five Guys",
		"2210952" : "Uptown Cafe",
		"207306"  : "Corner Bakery Courthouse",
		"41457"   : "Delhi Dhaba",
		"101161"  : "TNR Cafe",
		"257424"  : "Afghan Kabob House",
		"512060"  : "The Perfect Pita",
		"66244"   : "California Tortilla",
		"352867"  : "Pho 75 - Rosslyn",
		"22493"   : "Ragtime",
		"268052"  : "Subway",
		"5665"    : "Summers Restaurant & Sports Bar",
		"129724"  : "Cosi",
		"42599"   : "Ray's Hell Burger"
	};

	$(function() {

		var venueContainer = $('#venues ul');
		$.each(venues, function(key, item) {
			venueContainer.append(
		        $(document.createElement("li"))
		        .append(
	                $(document.createElement("input")).attr({
                         id:    'venue-' + key
                        ,name:  item
                        ,value: item
                        ,type:  'checkbox'
                        ,checked:true
	                })
	                .change( function() {
	                	var cbox = $(this)[0];
	                	var segments = wheel.segments;
	                	var i = segments.indexOf(cbox.value);

	                	if (cbox.checked && i == -1) {
	                		segments.push(cbox.value);

	                	} else if ( !cbox.checked && i != -1 ) {
	                		segments.splice(i, 1);
	                	}

	                	segments.sort();
	                	wheel.update();
	                } )

		        ).append(
	                $(document.createElement('label')).attr({
	                    'for':  'venue-' + key
	                })
	                .text( item )
		        )
		    )
		});

		$('#venues ul>li').tsort("input", {attr: "value"});
	});
</script>
<script type="text/javascript">
// WHEEL!
	var wheel = {

		timerHandle : 0,
		timerDelay : 33,

		angleCurrent : 0,
		angleDelta : 0,

		size : 290,

		canvasContext : null,

		colors : [ '#ffff00', '#ffc700', '#ff9100', '#ff6301', '#ff0000', '#c6037e',
		           '#713697', '#444ea1', '#2772b2', '#0297ba', '#008e5b', '#8ac819' ],

		//segments : [ 'Andrew', 'Bob', 'Fred', 'John', 'China', 'Steve', 'Jim', 'Sally', 'Andrew', 'Bob', 'Fred', 'John', 'China', 'Steve', 'Jim'],
		segments : [],

		seg_colors : [], // Cache of segments to colors
		
		maxSpeed : Math.PI / 16,

		upTime : 1000, // How long to spin up for (in ms)
		downTime : 17000, // How long to slow down for (in ms)

		spinStart : 0,

		frames : 0,

		centerX : 300,
		centerY : 300,

		spin : function() {

			// Start the wheel only if it's not already spinning
			if (wheel.timerHandle == 0) {
				wheel.spinStart = new Date().getTime();
				wheel.maxSpeed = Math.PI / (16 + Math.random()); // Randomly vary how hard the spin is
				wheel.frames = 0;
				wheel.sound.play();

				wheel.timerHandle = setInterval(wheel.onTimerTick, wheel.timerDelay);
			}
		},

		onTimerTick : function() {

			wheel.frames++;

			wheel.draw();

			var duration = (new Date().getTime() - wheel.spinStart);
			var progress = 0;
			var finished = false;

			if (duration < wheel.upTime) {
				progress = duration / wheel.upTime;
				wheel.angleDelta = wheel.maxSpeed
						* Math.sin(progress * Math.PI / 2);
			} else {
				progress = duration / wheel.downTime;
				wheel.angleDelta = wheel.maxSpeed
						* Math.sin(progress * Math.PI / 2 + Math.PI / 2);
				if (progress >= 1)
					finished = true;
			}

			wheel.angleCurrent += wheel.angleDelta;
			while (wheel.angleCurrent >= Math.PI * 2)
				// Keep the angle in a reasonable range
				wheel.angleCurrent -= Math.PI * 2;

			if (finished) {
				clearInterval(wheel.timerHandle);
				wheel.timerHandle = 0;
				wheel.angleDelta = 0;

				$("#counter").html((wheel.frames / duration * 1000) + " FPS");
			}

			/*
			// Display RPM
			var rpm = (wheel.angleDelta * (1000 / wheel.timerDelay) * 60) / (Math.PI * 2);
			$("#counter").html( Math.round(rpm) + " RPM" );
			 */
		},

		init : function(optionList) {
			try {
				wheel.initWheel();
				wheel.initAudio();
				wheel.initCanvas();
				wheel.draw();

				$.extend(wheel, optionList);

			} catch (exceptionData) {
				alert('Wheel is not loaded ' + exceptionData);
			}

		},

		initAudio : function() {
			var sound = document.createElement('audio');
			sound.setAttribute('src', 'wheel.mp3');
			wheel.sound = sound;
		},

		initCanvas : function() {
			var canvas = $('#wheel #canvas').get(0);

			if ($.browser.msie) {
				canvas = document.createElement('canvas');
				$(canvas).attr('width', 1000).attr('height', 600).attr('id', 'canvas').appendTo('.wheel');
				canvas = G_vmlCanvasManager.initElement(canvas);
			}

			canvas.addEventListener("click", wheel.spin, false);
			wheel.canvasContext = canvas.getContext("2d");
		},

		initWheel : function() {
			shuffle(wheel.colors);
		},

		// Called when segments have changed
		update : function() {
			// Ensure we start mid way on a item
			//var r = Math.floor(Math.random() * wheel.segments.length);
			var r = 0;
			wheel.angleCurrent = ((r + 0.5) / wheel.segments.length) * Math.PI * 2;

			var segments = wheel.segments;
			var len      = segments.length;
			var colors   = wheel.colors;
			var colorLen = colors.length;

			// Generate a color cache (so we have consistant coloring)
			var seg_color = new Array();
			for (var i = 0; i < len; i++)
				seg_color.push( colors [ segments[i].hashCode().mod(colorLen) ] );

			wheel.seg_color = seg_color;

			wheel.draw();
		},

		draw : function() {
			wheel.clear();
			wheel.drawWheel();
			wheel.drawNeedle();
		},

		clear : function() {
			var ctx = wheel.canvasContext;
			ctx.clearRect(0, 0, 1000, 800);
		},

		drawNeedle : function() {
			var ctx = wheel.canvasContext;
			var centerX = wheel.centerX;
			var centerY = wheel.centerY;
			var size = wheel.size;

			ctx.lineWidth = 1;
			ctx.strokeStyle = '#000000';
			ctx.fileStyle = '#ffffff';

			ctx.beginPath();

			ctx.moveTo(centerX + size - 40, centerY);
			ctx.lineTo(centerX + size + 20, centerY - 10);
			ctx.lineTo(centerX + size + 20, centerY + 10);
			ctx.closePath();

			ctx.stroke();
			ctx.fill();

			// Which segment is being pointed to?
			var i = wheel.segments.length - Math.floor((wheel.angleCurrent / (Math.PI * 2))	* wheel.segments.length) - 1;

			// Now draw the winning name
			ctx.textAlign = "left";
			ctx.textBaseline = "middle";
			ctx.fillStyle = '#000000';
			ctx.font = "2em Arial";
			ctx.fillText(wheel.segments[i], centerX + size + 25, centerY);
		},

		drawSegment : function(key, lastAngle, angle) {
			var ctx = wheel.canvasContext;
			var centerX = wheel.centerX;
			var centerY = wheel.centerY;
			var size = wheel.size;

			var segments = wheel.segments;
			var len = wheel.segments.length;
			var colors = wheel.seg_color;

			var value = segments[key];
			
			ctx.save();
			ctx.beginPath();

			// Start in the centre
			ctx.moveTo(centerX, centerY);
			ctx.arc(centerX, centerY, size, lastAngle, angle, false); // Draw a arc around the edge
			ctx.lineTo(centerX, centerY); // Now draw a line back to the centre

			// Clip anything that follows to this area
			//ctx.clip(); // It would be best to clip, but we can double performance without it
			ctx.closePath();

			ctx.fillStyle = colors[key];
			ctx.fill();
			ctx.stroke();

			// Now draw the text
			ctx.save(); // The save ensures this works on Android devices
			ctx.translate(centerX, centerY);
			ctx.rotate((lastAngle + angle) / 2);

			ctx.fillStyle = '#000000';
			ctx.fillText(value.substr(0, 20), size / 2 + 20, 0);
			ctx.restore();

			ctx.restore();
		},

		drawWheel : function() {
			var ctx = wheel.canvasContext;

			var angleCurrent = wheel.angleCurrent;
			var lastAngle    = angleCurrent;

			var segments  = wheel.segments;
			var len       = wheel.segments.length;
			var colors    = wheel.colors;
			var colorsLen = wheel.colors.length;

			var centerX = wheel.centerX;
			var centerY = wheel.centerY;
			var size    = wheel.size;

			var PI2 = Math.PI * 2;

			ctx.lineWidth    = 1;
			ctx.strokeStyle  = '#000000';
			ctx.textBaseline = "middle";
			ctx.textAlign    = "center";
			ctx.font         = "1.4em Arial";

			for (var i = 1; i <= len; i++) {
				var angle = PI2 * (i / len) + angleCurrent;
				wheel.drawSegment(i - 1, lastAngle, angle);
				lastAngle = angle;
			}
			// Draw a center circle
			ctx.beginPath();
			ctx.arc(centerX, centerY, 20, 0, PI2, false);
			ctx.closePath();

			ctx.fillStyle   = '#ffffff';
			ctx.strokeStyle = '#000000';
			ctx.fill();
			ctx.stroke();

			// Draw outer circle
			ctx.beginPath();
			ctx.arc(centerX, centerY, size, 0, PI2, false);
			ctx.closePath();

			ctx.lineWidth   = 10;
			ctx.strokeStyle = '#000000';
			ctx.stroke();
		},
	}

	window.onload = function() {
		wheel.init();

		var segments = new Array();
		$.each($('#venues input:checked'), function(key, cbox) {
			segments.push( cbox.value );
		});

		wheel.segments = segments;
		wheel.update();

		// Hide the address bar (for mobile devices)!
		setTimeout(function() {
			window.scrollTo(0, 1);
		}, 0);
	}
</script>
</head>
<body>
<div id="venues" style="float:left"><ul><li><input id="venue-257424" name="Afghan Kabob House" value="Afghan Kabob House" type="checkbox" checked="checked"><label for="venue-257424">Afghan Kabob House</label></li><li><input id="venue-66244" name="California Tortilla" value="California Tortilla" type="checkbox" checked="checked"><label for="venue-66244">California Tortilla</label></li><li><input id="venue-207306" name="Corner Bakery Courthouse" value="Corner Bakery Courthouse" type="checkbox" checked="checked"><label for="venue-207306">Corner Bakery Courthouse</label></li><li><input id="venue-129724" name="Cosi" value="Cosi" type="checkbox" checked="checked"><label for="venue-129724">Cosi</label></li><li><input id="venue-41457" name="Delhi Dhaba" value="Delhi Dhaba" type="checkbox" checked="checked"><label for="venue-41457">Delhi Dhaba</label></li><li><input id="venue-392360" name="Five Guys" value="Five Guys" type="checkbox" checked="checked"><label for="venue-392360">Five Guys</label></li><li><input id="venue-5518" name="Ireland's Four Courts" value="Ireland's Four Courts" type="checkbox" checked="checked"><label for="venue-5518">Ireland's Four Courts</label></li><li><input id="venue-116208" name="Jerry's Subs and Pizza" value="Jerry's Subs and Pizza" type="checkbox" checked="checked"><label for="venue-116208">Jerry's Subs and Pizza</label></li><li><input id="venue-352867" name="Pho 75 - Rosslyn" value="Pho 75 - Rosslyn" type="checkbox" checked="checked"><label for="venue-352867">Pho 75 - Rosslyn</label></li><li><input id="venue-22493" name="Ragtime" value="Ragtime" type="checkbox" checked="checked"><label for="venue-22493">Ragtime</label></li><li><input id="venue-42599" name="Ray's Hell Burger" value="Ray's Hell Burger" type="checkbox" checked="checked"><label for="venue-42599">Ray's Hell Burger</label></li><li><input id="venue-66271" name="Starbucks" value="Starbucks" type="checkbox" checked="checked"><label for="venue-66271">Starbucks</label></li><li><input id="venue-268052" name="Subway" value="Subway" type="checkbox" checked="checked"><label for="venue-268052">Subway</label></li><li><input id="venue-5665" name="Summers Restaurant &amp; Sports Bar" value="Summers Restaurant &amp; Sports Bar" type="checkbox" checked="checked"><label for="venue-5665">Summers Restaurant &amp; Sports Bar</label></li><li><input id="venue-512060" name="The Perfect Pita" value="The Perfect Pita" type="checkbox" checked="checked"><label for="venue-512060">The Perfect Pita</label></li><li><input id="venue-101161" name="TNR Cafe" value="TNR Cafe" type="checkbox" checked="checked"><label for="venue-101161">TNR Cafe</label></li><li><input id="venue-2210952" name="Uptown Cafe" value="Uptown Cafe" type="checkbox" checked="checked"><label for="venue-2210952">Uptown Cafe</label></li></ul></div>
<div id="wheel">
<canvas height="600" id="canvas" width="1000"></canvas>
</div>
<div id="stats">
<div id="counter">30.278136368970777 FPS</div>
</div>


</body></html>
반응형
반응형

TypeScript-Handbook 한글 문서,  TypeScript Handbook을 번역하는 프로젝트입니다.

 

https://typescript-kr.github.io/

 

TypeScript 한글 문서

TypeScript 한글 번역 문서입니다

typescript-kr.github.io

 

반응형
반응형

ECMA Script 6? 버전 특징

 

ES 2015 (ES 6)


1. let, const 키워드 추가
기존의 변수는 함수 scope를 가진 var 키워드를 이용하여 선언하였다. 때문에 block scope 를 가진 let과 const 키워드를 추가하였다. 기존에는 상수형 키워드가 없어 CONST_TEST와 같이 대문자로 상수임을 표시했다면, ES 6부터 const 키워드가 추가되어 값의 변경을 통제한다.

2. arrow 문법 지원
arror 문법은 두 가지의 장점을 제공한다. 첫 번째는 익숙하면 편하고 간결해진 코드를 작성할 수 있다. 두 번째는 this 를 바인딩하지 않는다. (다르게 말하면, this는 해당 scope의 this와 같다.)
두 번째 this를 바인딩 하지 않는다는 코드로 설명하겠다. 우선 아래 코드를 보자. test 객체에 name변수와 fn이라는 메소드를 두었다. 아래 test.fun으로 메소드를 실행한다.

3. iterator / generator 추가
위 arrorw에서 샛길로 빠져서 더 새진 않겠습니다. 이 둘은 따로 공부해서 글을 쓸 정도로 내용이 깊고 많습니다.

4. module import / export 추가
사실 저는 익숙하고 당연하게 import / export를 써 왔는데 도입된 시점이 그리 오래되지 않았다는 것에 잠깐 놀라네요.

5. Promise 도입
자바스크립트의 비 동기 callback hell을 해결해 줄 기법이 추가 되었습니다.

ECMA 2017 (ES 8)

사실 ECMA 2017 까진 정리하지 않으려 했는데, 보던 중 반가운 기능이 추가되어 소개 합니다.
async — await
위에서 ES6에서 callback hell을 해결하기 위해 Promise가 도입되었다고 했는데 async-await도 Promise처럼 callback 을 해결할 뿐만 아니라 좀 더 직관적이고 단순하게 코드를 만들 수 있습니다.
반응형

+ Recent posts