2017-12-15 7 views
-1

저는 현재 JavaScript로 2D 그래픽 라이브러리를 개발하고 있습니다. 이제는 문제를 변형시키는 배경 텍스처를 고수하고 있습니다.JavaScript 캔버스 fillingStyle에서 이미지 패턴을 변환하는 방법은 무엇입니까?

이미지 (CanvasPattern)에 캔버스 컨텍스트 (CanvasRenderingContext2D)의 배경 텍스처 (속성 fillStyle)를 설정하고 싶습니다. fillStyle에 이미지를 지정하는 것은 쉽습니다. 하지만 문제는 이미지를 실제로 번역하거나 크기를 조정하거나 왜곡 할 수 없다는 것입니다.

MDN을 찾았습니다. setTransform()이라는 프로토 타입이 있다고합니다. 이 API를 사용하면 이미지를 SVGMatrix으로 변형 할 수 있습니다. 약간 짜증이납니다. <svg> 중복 요소를 만들어야 할뿐만 아니라 실험용 API이기도하며 Google 크롬에서는 작동하지 않습니다.

일반적인 방법으로 해결하는 것은 불가능합니다. 이 작업을 수행하는 '해킹'방법이 있습니까?

+0

당신은 먼저 다음 경로가 설정 만든 후 경로를 별도로 변환 생성 사용하여 경로의 채우기 독립을 변형 할 수 있습니다 당신이 패턴 원하는 변환을 한 후 채우기 .. 예 :'ctx.beginPath(); ctx.rect (0, 0, ctx.canvas.width, ctx.canvas.height); ctx, rotate (1); ctx.fillStyle = 패턴; 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 경로가 유지 설정.

이 예제에서는 패턴을 두 개의 상자 안에 회전합니다.

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>

관련 문제