2013년 9월 21일 토요일

Processing sin() cos() 예제

Processing sin() cos() 예제













이 소스는 http://makeprocessing.com/ 에서 가져와 수정했습니다.

2013년 9월 20일 금요일

ProcessingJS 란?

[Processing 언어를 안다는 전제하에 작성합니다]

ProcessingJS 란?

 일단 전제조건이 html5 의 canvas 기능을 사용할 수 있는 브라우저에서만 동작합니다. (결국 IE8 이하 버전에선 동작 안한다는 말과 같습니다)
ProcessingJS는 기존의 Processing 언어를 자바스크립트 라이브러리로 만들어 놓은 것인데, 특이하게 코딩방법이 3가지입니다.


  1.  processing.js 라이브러리 파일과,   .html 파일만 으로 코딩
  2.  processing.js 와 .pde 프로세싱파일, .html 파일

 파일 구성으로만 보면 2가지 이지만 첫번째 html 파일에서 코딩하는 방법이 또 2가지로 나뉩니다.

  1. 평범하게 프로세싱언어로 void setup(), void draw() 등으로 코딩
  2. 자바스크립트와 혼용하여 void 가 아닌 function processing.draw() 로 코딩

 말로 설명 드리면 어려울 것 같아 앞서 포스팅한 '프로세싱 간단예제 1,2 페이지를 보시면 됩니다. 

 개인적인 생각으론 웹에서만 쓴다면 자바스크립트와 혼용하여 쓰는 것이 가장 좋은 방법으로 보입니다만 자동적으로 파싱해주는 프로그램같은 무엇인가가 없어서 한가지 코드로 pc용, 안드로이드용, 웹용 등으로 컴파일 할 수 있는 프로세싱만의 장점중 하나를 버려야 합니다.
 이 블로그에서는 일반 프로세싱 코드로만 작성하겠습니다. pde 파일을 쓸 수 있으면 좋겠지만 따로 호스팅이나 첨부할 곳이 마땅치 않아 위에 언급한 첫번째 방법으로 코딩하겠습니다.
이유는 제가 하고자 하는것이 프로세싱으로 안드로이드 게임(액션)을 만드는 것이므로...어디까지 해낼지는 모르겠지만 틈나는 대로 테스트한 코드와 팁들을 포스팅하겠습니다.




추신- 안드로이드 게임을 프로세싱으로 만들려는 이유는.. 아주 기초적인 안드로이드용 자바를 알지만 게임엔진등을 이용해 만들만한 자바실력이 안되고, 개인이 쉽게 구할수 있는 2d 게임엔진이 너무 없기 때문입니다. 아이폰의 경우 c#을 몰라도 앱을 제작할 수 있는 툴들이 많은 반면, 안드로이드에도 같은 툴들이 많았으나 거의 대부분 개발 중단된 상태입니다. 찾다보니 프로세싱언어가 있었고, 프로세싱,안드로이드 둘다 자바기반이라 그런지 프로세싱에서 안드로이드의 motionEvent() 같은 이벤트(?)를 상속받아 사용할 수 있어서 프로세싱으로 도전하려고 합니다. 


ProcessingJS 간단예제 2

ProcessingJS 간단예제 2



<script src="https://github.com/downloads/processing-js/processing-js/processing-1.4.1.min.js"></script>
<script data-processing-target="mycanvas" type="text/processing">
float radius = 50.0;
int X, Y;
int nX, nY;
int delay = 16;

// Setup the Processing Canvas
void setup(){
  size( 200, 200 );
  strokeWeight( 10 );
  frameRate( 30 );
  X = width / 2;
  Y = height / 2;
  nX = X;
  nY = Y;
}

// Main draw loop
void draw(){

  radius = radius + sin( frameCount / 4 );

  // Track circle to new destination
  X+=(nX-X)/delay;
  Y+=(nY-Y)/delay;

  // Fill canvas grey
  background( 100 );

  // Set fill-color to blue
  fill( 0, 121, 184 );

  // Set stroke-color white
  stroke(255);

  // Draw circle
  ellipse( X, Y, radius, radius );                
}


// Set circle's next destination
void mouseClicked(){
  nX = mouseX;
  nY = mouseY;
}
</script>
<canvas id="mycanvas"></canvas>

2013년 9월 19일 목요일

ProcessingJS 간단예제1


Simple processing.js via JavaScript

Simple PorcessingJS examples

ProcessingJS 간단 시계 예제


Clock


<script src="https://github.com/downloads/processing-js/processing-js/processing-1.4.1.min.js"></script>

<canvas height="200" id="canvas1" width="200"></canvas>

<script id="script1" type="text/javascript">

// Simple way to attach js code to the canvas is by using a function
function sketchProc(processing) {
  // Override draw function, by default it will be called 60 times per second
  processing.draw = function() {
    // determine center and max clock arm length
    var centerX = processing.width / 2, centerY = processing.height / 2;
    var maxArmLength = Math.min(centerX, centerY);

    function drawArm(position, lengthScale, weight) {    
      processing.strokeWeight(weight);
      processing.line(centerX, centerY,
        centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,
        centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);
    }

    // erase background
    processing.background(224);

    var now = new Date();

    // Moving hours arm by small increments
    var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
    drawArm(hoursPosition, 0.5, 5);

    // Moving minutes arm by small increments
    var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;
    drawArm(minutesPosition, 0.80, 3);

    // Moving hour arm by second increments
    var secondsPosition = now.getSeconds() / 60;
    drawArm(secondsPosition, 0.90, 1);
  };

}

var canvas = document.getElementById("canvas1");
// attaching the sketchProc function to the canvas
var p = new Processing(canvas, sketchProc);
// p.exit(); to detach it
</script>


<canvas id="mycanvas"></canvas>

2013년 8월 26일 월요일

Jqeury Aajax 사용시 데이터 깜빡임

 예를들어 리스트를 출력 할 때, 계속 해서 리스트를 새로부르거나 하면 0.1초가량 아주 잠깐 바로 전 리스트값이 보였다가 새로운 리스트가 보이는데, 
$(document).ready( function () {       를 
 $(window).load( function () {
이렇게 바꿔주면된다.

document.ready 화면 출력과 상관없이, dom 정보만 받아왔으면 바로 시작된다.

 window.onload 는 모든 화면이 로드 된 뒤에 작동한다.

2013년 8월 25일 일요일

HTML 강제 줄바꿈

overflow 시 줄바꿈

<element style="word-break:break-all">

Canvas 이미지 저장(다운로드하는법)

canvas 다운로드 방법

var data = canvas.toDataURL();

아래의 a 테그의 href 를 data 로 바꿔주면된다. 크롬만 가능(크롬프레임도 됨)

<a href="#" class="downlink" download="gray.png"><input type='button' value='wwwww'></a>


참고 
http://html5-demos.appspot.com/static/filesystem/generatingResourceURIs.html



<article>
    <button type="button">create url, put it in below link, and click it</button><br/>
    <download="test.txt">Download as text.txt</a>
</article>
<footer>
<ul>
    <li><href="https://developer.mozilla.org/en/Document_Object_Model_(DOM)/window.URL.createObjectURL">window.URL.createObjectURL</a></li>
    <li><href="http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download">a[download]</a></li>
    <br/>
    <br/>
    <br/>
    <br/>
    <li><href="it works!" download="nate.txt">download me</a></li>
</ul>
</footer>


var URL window.webkitURL || window.URL;
var BlobBuilder window.WebKitBlobBuilder || window.MozBlobBuilder || window.BlobBuilder;

var url;

$("button").click(function({
    if (urlURL.revokeObjectURL(url);
    var bb new BlobBuilder();
    bb.append("it workwfwefwefwefwefwefwefwefwefs!");
    var file bb.getBlob("text/plain");
    url URL.createObjectURL(file);
    $("a[download]").attr("href"url);
    
    var evt document.createEvent('MouseEvents');
    evt.initMouseEvent('click'truetruewindow10000falsefalsefalsefalse0null);
    $("a[download]")[0].dispatchEvent(evt);
});

자바스크립트 대문자 소문자 변환

toLowerCase();  소문자로 바꿔주는 함수  
toUpperCase() ;  대문자로 바꿔주는 함수






자바스크립트 대문자를 소문자로 소문자를 대문자로 바꾸는 함수

var abcd = "AbCd";

abcd = abcd.toLowerCase();
console.log(abcd) // abcd = "abcd"

abcd = abcd.toUpperCase();
console.log(abcd) // abcd = "ABCD"


 

비쥬얼 스튜디오 인코딩 문제

1. Visual Studio 설치된 위치(보통 C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcprojectitems)에 간다.

2. hfile.h, newc++file.cpp 과 같은 템플릿 파일의 인코딩을 UTF-8로 변경한다
3. 그 뒤로는 항상 UTF-8 파일이 생성된다.

node.js for II7

blueimp jquery upload component server 을 win IIS7 에서 구동.
준비물 및 환경

OS : win7
iisnode : iisnode-full-iis7-v0.1.18-x86.msi
다운로드사이트 : https://github.com/tjanczuk/iisnode/
nodejs : node-v0.6.18.msi
다운로드사이트 : http://www.nodejs.org/



  1. iis 에 iisnode 폴더를 사이트로 등록.
  2. web.config 파일을 만들어준다.
  3. helloworld 파일내에 webconfig 안의 add name 부분을 자신의 서버 파일명으로 바꿔준다 ex) hello.js 를 server.js파일로 바꿔준다.
  4. node.js 소스 파일을 helloworld 폴더에 넣는다.
  5. node.js 파일에서 쓰는 포트와 아이피는  IIS 에서 쓰는 포트와 아이피를 사용해야 하므로, 직접입력하지 않고 process.env.PORT / process.env.IP 이렇게 바꿔준다.
  6. iis 왼쪽 사이트 목록에서 iisnode 사이트를 선택 후 홈 화면의 '기본문서' 에 서버 파일을 등록한다.
해당 사이트로 접속 해보고 404 에러 (500 에러아님) 가 뜨면 정상적으로 서버가 실행된 것.


iis 에 등록하지 않고 node 파일의 실행법
CMD 에서 파일경로/node 파일명 ex) c:/node abc.js



<!-- web.config 내용 -->
<configuration>
<system.webServer>
<!-- indicates that the hello.js file is a node.js application
to be handled by the iisnode module -->
<handlers>
<add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>
<defaultDocument>
<files>
<add value="server.js" />
</files>
</defaultDocument>
</system.webServer>


</configuration>

node.js IDE Cloud9


 웹상에서 코딩이 가능한 IDE.   익스플로러는 지원하지 않으며, node.js, PHP, html5, Wordpress, Python/Django , Ruby on Rails, C/C++ 추가로 커스텀을 선택하여 디버깅을 할 수있습니다. 
 c9 는 node.js 에서 하기 힘들었던 디버깅을 visual studio 처럼 중단점을 찍고, 디버깅모드로 한단계식 실행도 가능합니다. 브라우저 상에서 실행되지만, 다양한 단축키들이 모두 동작됩니다. F5 라던지 ctrl + S 저장 이라던지.. 저장을 하면 바로 웹서버에 저장이 됩니다. 


디버깅 중인 화면 





node.js 이미지 편집모듈

imagemagick  이라는 모듈이 있다.
설치는 npm install imagemagick

리사이즈 옵션

                    imageMagick.resize({
                         width: opts.width,
                         height: opts.height,
                         srcPath: options.uploadDir + '/' + fileInfo.name,
                         dstPath: options.uploadDir + '/' + "thumb_"+origin_img_name
                    }, finish);

resize 옵션 사용법.

* eps 파일이  input 되면 jpg 로 출력된다

node.js 우분투에 설치


sudo apt-get install g++ curl libssl-dev apache2-utils

sudo apt-get install git-core

git clone git://github.com/ry/node.git

wget http://nodejs.org/dist/v0.8.4/node-v0.8.4.tar.gz

gunzip node-v0.8.4.tar.gz

tar -xf node-v0.8.4.tar

cd node

./configure

make

sudo make install


Node.js 의 설치의 설치 경로는 /usr/local/bin/ 이다.
모듈의 경로는 /ib/node_modules/  에 위치한다.