2017-12-15 21 views
-1

私は現在、JavaScriptで2Dグラフィックライブラリを開発していますが、今は問題を変換する背景テクスチャを固執しています。JavaScriptキャンバスのfillStyleでイメージパターンを変換する方法は?

イメージ(CanvasPattern)にキャンバスコンテキスト(CanvasRenderingContext2D)の背景テクスチャ(プロパティfillStyle)を設定したいとします。 fillStyleに画像を割り当てるのは簡単です。 しかし、唯一の問題は、画像を実際に翻訳、縮尺変更、または歪曲することができないことです。

私はMDNを調べました。setTransform()というプロトタイプがあります。 このAPIを使用すると、画像をSVGMatrixで変換できますが、これは少し面倒です。 冗長<svg>要素を作成するだけでなく、実験的なAPIでもあり、Google Chromeでは動作しません。

通常の方法では解決できません。 これを行うための 'ハックな'方法はありますか?

+0

あなたは、パスが作成された後、最初にパスを作成し、別途変換を使用して、パスの塗りつぶしの独立を変換することができますが、パターンのために欲しいものに変換してから埋め設定..例えば 'ctx.beginPath(); ctx.rect(0、0、ctx.canvas.width、ctx.canvas.height); ctx、rotate(1); ctx.fillStyle = pattern; ctx.fill(); ' – Blindman67

答えて

0

CanvasRenderingContext2Dでは変換をCanvasPatternではなく設定します。これははるかにサポートされており、SVGMatrixオブジェクトをニートする必要はありません。

結果の塗りつぶし領域は変形された領域であるため、キャンバス全体を均一なパターンにしたい場合にのみ有効です。

var canvas = document.getElementById('canvas'); 
 
var ctx = canvas.getContext('2d'); 
 

 
var img = new Image(); 
 
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; 
 
img.onload = function() { 
 
    var pattern = ctx.createPattern(img, 'repeat'); 
 
    ctx.fillStyle = pattern; 
 
    ctx.setTransform(0.8, 0.3, 0, 0.8, 0, 0) 
 
    ctx.fillRect(0, -172, 450, 700); //make sure the whole canvas is covered 
 
};
<canvas id="canvas" width="400" height="400"></canvas>

1

まず塗りつぶしが変換されている間、それがあった場所のままtransform.Theパスを設定し、パスを描画します。

この例では、パターンを2つのボックスの内側に回転しています。

const ctx = canvas.getContext('2d'); 
 
var pattern; 
 

 
const img = new Image(); 
 
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; 
 
img.onload =() => pattern = ctx.createPattern(img, 'repeat'); 
 

 

 

 
requestAnimationFrame(mainLoop); 
 
function mainLoop(time){ 
 
    ctx.setTransform(1,0,0,1,0,0); 
 
    ctx.clearRect(0,0,canvas.width,canvas.height); 
 

 
    ctx.fillStyle = pattern; 
 

 
    ctx.beginPath(); 
 
    ctx.setTransform(1,0,0,1,0,0); 
 
    ctx.rect(100,100,200,200); // create the path for rectangle 
 
    ctx.setTransform(1,0,0,1,300,200); // Set the transform for the pattern 
 
    ctx.rotate(time/1000); 
 
    ctx.fill(); 
 

 

 
    ctx.beginPath(); 
 
    ctx.setTransform(1,0,0,1,0,0); 
 
    ctx.rect(150,0,100,400); // create the path for the rectangle 
 
    ctx.setTransform(0.2,0,0,0.2,150,200); // Set the transform for the pattern 
 
    ctx.rotate(-time/1000); 
 
    ctx.fill(); 
 

 
    requestAnimationFrame(mainLoop); 
 
}
<canvas id="canvas" width="400" height="400" style="border:2px solid black;"></canvas>

関連する問題