使用ES6或ES5,有没有办法避免在管理图像属性和方法时一遍又一遍地连续输入ctx?意思是如果我有以下代码:
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// Filled triangle
ctx.beginPath();
ctx.moveTo(25, 25);
ctx.lineTo(105, 25);
ctx.lineTo(25, 105);
ctx.fill();
// Stroked triangle
ctx.beginPath();
ctx.moveTo(125, 125);
ctx.lineTo(125, 45);
ctx.lineTo(45, 125);
ctx.closePath();
ctx.stroke();
}
}
我们可以做一些类似的事情吗
ctx = { //parent name here only once
//then all properties or methods associated to it here...
}
最佳答案
这是使用 with
的示例
但是要小心过度使用它,Javascript 上下文可能会变得困惑,过度使用 with
会使情况变得更糟。
但是对于像这样简单的事情,我看不出有什么问题。
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
with (ctx) {
// Filled triangle
beginPath();
moveTo(25, 25);
lineTo(105, 25);
lineTo(25, 105);
fill();
// Stroked triangle
beginPath();
moveTo(125, 125);
lineTo(125, 45);
lineTo(45, 125);
closePath();
stroke();
}
}
}
draw();
<canvas id="canvas"></canvas>
关于javascript - 在 Canvas 中创建形状时减少 ctx 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288538/