Javascript HTML5画布-使用一系列命令通过上下文绘制?

Javascript HTML5画布-使用一系列命令通过上下文绘制?,javascript,html,canvas,Javascript,Html,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 = in

我想做如下的事情

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

做这样的事情最好的方法是什么?

我有点不明白您想要什么,但是javascript命令可能会有所帮助

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;
}
var命令=[];
commands.push(函数(上下文){
context.beginPath();
});
commands.push(函数(上下文){
上下文。moveTo(25,25);
上下文。lineTo(105,25);
lineTo(25105);
});
commands.push(函数(上下文){
context.fill();
});
document.body.appendChild(DrawToCanvas(commands,300300));
函数DrawToCanvas(命令、高度、宽度){
var canvas=document.createElement(“canvas”);
画布宽度=宽度;
canvas.height=高度;
var context=canvas.getContext(“2d”)
for(var i=0;i
有趣的是,在数组中存储函数而不是命令本身。为什么你要把它分成3个push语句,而不是把所有的事情都放在一个语句中?
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;
}