2012-08-07 79 views
0

我想要做類似下面的...HTML5畫布 - 使用一組命令通過上下文繪製?

// 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

我有點困惑,你在追求什麼,但javascript 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 2012-08-07 17:34:08