如何在编码时为 html canvas 一次又一次地跳过传递上下文

How to skip passing context again and again for html canvas while coding

我正在尝试使用 html canvas 制作一些东西,但我必须一次又一次地将上下文传递给每个函数。有没有办法以某种方式跳过或自动执行此任务?

例如在p5.js中我们只有 设置和绘制功能,没有额外的上下文等。 我想做同样的事情,但规模较小

 function render() { 
      console.log(data)
      // i have to pass context again and again to each function 
      drawPoint(context, new Vector(mousex, mousey), 6)
      drawPoint(context, new Vector(100, 100), 5, "red")
      drawPoint(context, new Vector(100, 100), 5, "red")
      drawPoint(context, new Vector(100, 100), 5, "red")
      drawPoint(context, new Vector(100, 100), 5, "red")
      requestAnimationFrame(render)
    }
    render()

我希望它像


function start(){
  // some global variables that may be accessed in 
  // the render function directly

}
function render(){
 // some code without passing any context
 drawpoint(new Vector(100, 100))

}

简单来说,我只想模仿与 p5.js 处理或 arduino ide 等相同的效果。 只有两个功能,一个用于设置,一个用于循环

有人知道ide怎么做吗?

制作你自己的功能?

function myDrawPoint  () {
    drawPoint.apply(null, [context, ...Object.values(arguments)]);
}

您可以使用高阶函数基本上给出一次上下文,然后重复调用该函数。

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

function createDrawPoint(context) {
  return (vector) => {
    console.log('drawPoint called with context', vector);
    // do something with context here
  };
}

const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const drawPoint = createDrawPoint(context);
drawPoint(new Vector(100, 100));
drawPoint(new Vector(100, 150));
drawPoint(new Vector(150, 100));

基本上,您创建的函数将 return 实际的 drawPoint() 函数,但 context 绑定在其范围内,因此您不必将其传入反复。

如果你愿意,你也可以用多种方法做同样的事情,就像这样。

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

function createDrawPoint(context) {
  return {
    drawPoint: (vector) => {
      console.log('drawPoint called with context', vector);
      // do something with context here
    },
    drawLine: (vectorA, vectorB) => {
      console.log('drawLine called with context', vector);
    }
  };
}

const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const { drawPoint, drawLine } = createDrawPoint(context);

drawPoint(new Vector(100, 100));
drawPoint(new Vector(100, 150));
drawPoint(new Vector(150, 100));
drawLine(new Vector(200, 200), new Vector(300, 300));

虽然如果你有多个,我可能会将它们分组到一个 class(或者如果你出于某种原因不喜欢 class 语法,则只是一个原型对象构造函数),除非这个程序字面上只使用这些功能。

class DrawHelper {
  constructor(context) {
    this.context = context;
  }
  
  drawPoint(vector) {
    console.log('drawPoint');
  }
  
  drawLine(a, b) {
    console.log('drawLine');
  }
}

class Vector {}

const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const drawHelper = new DrawHelper(context);

drawHelper.drawPoint(new Vector(100, 100));
drawHelper.drawPoint(new Vector(100, 200));

drawHelper.drawLine(new Vector(300, 300), new Vector(400, 400));