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

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

本文关键字:上下文 绘制 数组 Canvas 命令 HTML5      更新时间:2023-09-26

我想做下面这样的事情...

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

是否有一些等效于上下文命令[i]等...

我在想如果这是不可能的,另一种选择是传递回调函数。像...

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

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

我有点困惑你在追求什么,但 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;
}