2012-08-07 2 views
0

나는, HTML5 Canvas - 명령 배열을 사용하여 컨텍스트를 통해 그립니다.

// commmands - context commands to build primitives. 
// See comments in loop for example. 
function DrawToCanvas(commands, height, width){ 

    var canvas = document.createElement("canvas"); 
    canvas.width = inWidth; 
    canvas.height = inHeight; 
    var context = canvas.getContext("2d")  

    for(var i = 0; i < commands.length; i++){ 

     // Do Stuff like 
     // context.beginPath(); 
     // context.moveTo(25,25); 
     // context.lineTo(105,25); 
     // context.lineTo(25,105); 
     // context.fill(); 

     // context.commands[i] <- Something like this 
    } 

    return canvas; 
} 

이 가능 아니었다면 내가 생각

등 context.commands [I], 일부 동등한 ... 거기 ... 다음과 같은 일을 할 또 다른 옵션은 대신 콜백 함수를 전달하는 것입니다. 뭔가가 ...

function MakeALine(){ 

var newLineAsCanvas = DrawToCanvas(100,100,function(context){ 
    context.beginPath(); 
    context.moveTo(25,25); 
    // etc... 
} 
} 

이 작업을 수행하는 가장 좋은 방법은 무엇입니까?

답변

1

저는 약간 혼란 스럽지만, 자바 스크립트 call 명령이 도움이 될 것 같습니다.

var commands = []; 
commands.push(function(context) { 
    context.beginPath(); 
}); 
commands.push(function(context) { 
    context.moveTo(25,25); 
    context.lineTo(105,25); 
    context.lineTo(25,105); 
}); 
commands.push(function(context) { 
    context.fill(); 
}); 
document.body.appendChild(DrawToCanvas(commands, 300, 300)); 

function DrawToCanvas(commands, height, width){ 

    var canvas = document.createElement("canvas"); 
    canvas.width = width; 
    canvas.height = height; 
    var context = canvas.getContext("2d") 

    for(var i = 0; i < commands.length; i++){ 
     commands[i].call(this, context); 
    } 

    return canvas; 
} 
+0

흥미로운 것은 명령 자체 대신 배열에 함수를 저장하는 것입니다. 왜 모든 것을 하나씩 처리하는 대신 3 가지 진술로 나눴습니까? – Steffan