我试图使用html画布制作一些东西,但我必须一次又一次地将上下文传递给每个函数。有没有一种方法可以跳过或自动完成这项任务?
例如,在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等相同的效果。只有两个函数,一个用于设置,另一个用于循环
有人知道怎么做吗?
您可以使用一个高阶函数来基本上给出一次上下文,然后重复调用该函数。
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));
基本上,您创建的函数将返回实际的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 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));
创建自己的函数?
function myDrawPoint () {
drawPoint.apply(null, [context, ...Object.values(arguments)]);
}