简体   繁体   English

使用 HTML5 canvas 上下文作为原型

[英]Using HTML5 canvas context as a prototype

I am trying to modify some functionality of the canvas context object without having to alter any code that is using this.我正在尝试修改 canvas 上下文 object 的某些功能,而无需更改任何使用它的代码。 A solution for this by creating a Proxy object has been posted here: JS Proxying HTML5 canvas context .通过创建Proxy object 的解决方案已在此处发布: JS Proxying HTML5 canvas 上下文

My question is: Can this behaviour be achieved without relying on Proxy by using ctx as a prototype?我的问题是:通过使用ctx作为原型,可以在不依赖Proxy的情况下实现这种行为吗?

Directly using it like this像这样直接使用

let acx = Object.create(ctx, {})
acx.fillStyle = 'red'

results in the same Error messages as mentioned in the linked question导致与链接问题中提到的相同的错误消息

TypeError: 'set fillStyle' called on an object that
    does not implement interface CanvasRenderingContext2D.

on all ctx methods I've tested.在我测试过的所有 ctx 方法上。

In the linked question this is explained as CanvasRenderingContext2DPrototype not accepting the fake ctx object.在链接的问题中,这被解释为CanvasRenderingContext2DPrototype接受假 ctx object。 What exactly does accepting mean here?在这里接受到底是什么意思? Is there any way to fix this?有没有什么办法解决这一问题?

You can store the canvas context property descriptors, and redefine the properties/methods you want.您可以存储 canvas 上下文属性描述符,并重新定义所需的属性/方法。 this is a more complicated way of doing pretty much what a Proxy does.这是一种更复杂的方式来完成代理所做的工作。

 var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var prototype = Object.getPrototypeOf(ctx); var descriptors = Object.getOwnPropertyDescriptors(prototype); Object.defineProperties(prototype, { fillStyle: { get() { console.log("Getting fillStyle"); return descriptors.fillStyle.get.call(this); }, set(value) { console.log("Setting fillStyle to", value); descriptors.fillStyle.set.call(this, value); } }, fillRect: { value(x, y, w, h) { console.log("Drawing rectangle", x, y, w, h); return descriptors.fillRect.value.call(this, x, y, w, h); } } }); var canvas2 = document.querySelector("canvas"); var ctx2 = canvas2.getContext("2d"); ctx2.fillStyle = "red"; //>> Setting fillStyle to red ctx2.fillRect(10, 10, 100, 100); //>> Drawing rectangle 10 10 100 100
 <canvas id="canvas"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM