оптимизация кода javaScript
здравствуйте
я рисую в канвасе:
canvas=document.getElementById("canvas"); c=canvas.getContext("2d")
c.clearRect(0, 0, 1400, 150); c.beginPath(); c.moveTo(0, 0); c.lineTo(0, 100); c.stroke()
чтобы обращаться к процедурам рисования всегда приходится писать имя канваса c.можно как-то сделать канвас с. "активным" чтобы рисовать без обращения к имени с. ?? clearRect(0, 0, 1400, 150); beginPath(); moveTo(0, 0); lineTo(100, 100); stroke() |
Можно, но не нужно. Никто вас не поблагодарит:).
Вариант 1(deprecated, не работает в strict mode):
with(c) {
clearRect(0, 0, 1400, 150);
beginPath();
moveTo(0, 0);
lineTo(100, 100);
stroke()
}
Вариант 2(без возможности присвоения, типа fillColor='#xxx', только c.fillColor='#xxx'):
function bindProxy(obj) {
return new Proxy(obj, {
get(target, key, r) {
const value = Reflect.get(target, key, r);
if (typeof value === 'function')
return value.bind(target);
return value;
}
})
}
const { clearRect, beginPath, moveTo, lineTo, stroke } = bindProxy(c);
clearRect(0, 0, 1400, 150);
beginPath();
moveTo(0, 0);
lineTo(100, 100);
stroke()
Если очень хочется, то лучше воспользоваться вспомогательный библиотекой для рисования, коих мнжество на любой вкус. Плюсом будут всякие иные удобности. |
Цитата:
strokeStyle('#ff0000');
const ss = strokeStyle();
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
function bindProxy(obj) {
return new Proxy(obj, {
get(target, key, r) {
const targetproto = Object.getPrototypeOf(target);
const value = Reflect.getOwnPropertyDescriptor(targetproto, key).value;
//const value = Reflect.get(target, key, r);
if (value && typeof value === 'function') {
return value.bind(target);
} else {
const pget = Reflect.getOwnPropertyDescriptor(targetproto, key).get;
const pset = Reflect.getOwnPropertyDescriptor(targetproto, key).set;
if (pget && typeof pget === 'function') {
if (pset && typeof pset === 'function') {
return function (v) {
if (arguments.length === 0) return target[key];
target[key] = v;
};
} else {
return function (v) {
return target[key];
};
}
} else if (pset && typeof pset === 'function') {
return function (v) {
target[key] = v;
};
}
}
return value;
}
});
}
const { clearRect, strokeStyle, beginPath, moveTo, lineTo, stroke } = bindProxy(ctx);
clearRect(0, 0, 1400, 150);
strokeStyle('#ff0000');
console.log(strokeStyle());
beginPath();
moveTo(0, 0);
lineTo(100, 100);
stroke()
</script>
</body>
|
| Часовой пояс GMT +3, время: 00:32. |