簡體   English   中英

如何將 fillStyle 添加到 Path2D? JS Canvas

[英]How do I add fillStyle to Path2D? JS Canvas

在提出這個問題的日期這可能是不可能的,但是Path2D()可以在 function 內有一個fillStyle嗎? 示例: Path2D('M10 10 h10 v15 h -18 Z #ff00ff');

我知道我可以添加ctx.fillStyle = color; 前。

我可能會忽略前幾個人,他們說除非給出適當的解釋,否則如果其他人想出答案,我不能只看誰。

這確實是不可能的,並且有幾個原因。

Path2D 僅表示子路徑,因此,它只是向量,不包含其他信息。

填充和/或描邊是完全獨立的操作,在不同的時刻進行,通常甚至在與子路徑構造(GPU 與 CPU)不同的硬件上進行。

實際上fillStylestrokeStyle確實代表了無限大的表面,它們只會被當前的子路徑剪裁。
這些表面甚至可以自己響應矩陣變換,這允許我們用一個變換矩陣聲明一個子路徑,用另一個填充,用第三個進行描邊:

 const canvas = document.getElementById( 'canvas' ); const ctx = canvas.getContext( '2d' ); ctx.fillStyle = makePattern("red"); ctx.strokeStyle = makePattern("green"); let angle = Math.PI / 2; ctx.lineWidth = 10; // we define our path with normal transforms ctx.rect( 50, 50, 100, 100 ); anim(); function anim() { clear(); // now we play with transforms const cos = Math.cos(angle); const sin = Math.sin(angle); ctx.setTransform( cos, sin, -sin, cos, 125, 125); ctx.translate( -25, -25 ); ctx.fill(); ctx.scale( cos * 5, cos * 5 ); ctx.stroke(); angle += Math.PI/360; requestAnimationFrame( anim ); } // jus make a checkerboard, each rect as 5x5px function makePattern( color ) { const ctx = Object.assign(canvas.cloneNode(), { width: 10, height: 10 }).getContext( '2d' ); ctx.fillStyle = color; ctx.rect(0,0,5,5); ctx.rect(5,5,5,5); ctx.fill(); return ctx.createPattern( ctx.canvas, 'repeat' ); } function clear() { ctx.setTransform( 1, 0, 0, 1, 0, 0 ); ctx.clearRect( 0, 0, canvas.width, canvas.height ); }
 <canvas id="canvas" height="300"></canvas>

不僅如此,即使對於isPointInFillisPointInStroke等方法,當前上下文設置也將決定這些方法的行為方式:

 const ctx = document.createElement('canvas').getContext( '2d' ); const path = new Path2D(); path.rect(50, 50, 50, 50); ctx.lineWidth = 1; console.log( 'with lineWidth 1', ctx.isPointInStroke( path, 46, 46 ) ); // false ctx.lineWidth = 10; console.log( 'with lineWidth 10', ctx.isPointInStroke( path, 46, 46 ) ); // true ctx.scale( 0.1, 0.1 ); console.log( 'after scaling down', ctx.isPointInStroke( path, 46, 46 ) ); // false ctx.setTransform( 1, 0, 0, 1, 0,0 ); console.log( 'after resetting the transform', ctx.isPointInStroke( path, 46, 46 ) ); // true ctx.setLineDash( [ 50, 50 ] ) console.log( 'after setting the line dash', ctx.isPointInStroke( path, 46, 46 ) ); // false

如您所見,許多參數可以改變路徑將如何被不同的 API 渲染/使用。 在 Path2D 實例本身上進行所有這些設置將使 object 與 2D 上下文一樣重,這不是我們想要的:
Path2d 接口是故意做輕量級的,這樣我們就可以存儲很多這些,並且我們可以盡可能快地使用它。 你仍然可以嘗試用一個可靠的用例來說明whatwg的觀點,所以他們考慮在規范中添加這樣的東西,但我強烈懷疑他們會......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM