简体   繁体   English

HTML5 Canvas-使用命令数组通过上下文绘制吗?

[英]HTML5 Canvas - Using an array of commands to draw via context?

I want to do something like the following... 我想做以下事情...

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

Is there some equivalent to context.commands[i], etc... 是否有一些等效于context.commands [i]等的东西?

I was thinking if this wasn't possible, another option would be to pass a callback function instead. 我在想如果这不可能,另一种选择是改为传递一个回调函数。 Something like... 就像是...

function MakeALine(){

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

What would be the best way to do something like this? 做这样的事情的最好方法是什么?

I'm a little confused what you're after, but the javascript call command is likely to help. 我对您的追求感到有些困惑,但是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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM