簡體   English   中英

使用 HTML5 canvas 上下文作為原型

[英]Using HTML5 canvas context as a prototype

我正在嘗試修改 canvas 上下文 object 的某些功能,而無需更改任何使用它的代碼。 通過創建Proxy object 的解決方案已在此處發布: JS Proxying HTML5 canvas 上下文

我的問題是:通過使用ctx作為原型,可以在不依賴Proxy的情況下實現這種行為嗎?

像這樣直接使用

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

導致與鏈接問題中提到的相同的錯誤消息

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

在我測試過的所有 ctx 方法上。

在鏈接的問題中,這被解釋為CanvasRenderingContext2DPrototype接受假 ctx object。 在這里接受到底是什么意思? 有沒有什么辦法解決這一問題?

您可以存儲 canvas 上下文屬性描述符,並重新定義所需的屬性/方法。 這是一種更復雜的方式來完成代理所做的工作。

 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