2016-11-09 1 views
0

기본적으로 주어진 다각형에 대해 폴 오프 텍스처를 만들어야합니다. 예를 들어이 내가 다각형 주위에 그라데이션 경사를 그립니다.

enter image description here

내가 작성해야하는 것은 이것이다

이 이미지이지만, 검은 색 흰색에서 경사 구배로, 그라데이션 등의 녹색 부분을 고려하십시오.

enter image description here

나는 모든 정점의 좌표와 베벨의 두께를 가지고있다. HTML5 2D 캔버스를 사용하여 렌더링 중입니다. 기본적으로 가장 확실한 해결책은 다각형에 대한 모든 픽셀의 거리를 계산하는 것이고 두께 매개 변수 내에 있으면 픽셀을 계산하여 색상을 지정하십시오. 하지만 그것은 무거운 계산이며 느린 것입니다. 심지어 가장 작은 텍스처에 대해서도 필요합니다. 그래서 이것을 달성하기 위해 캔버스로 할 수있는 트릭이 있습니까?

답변

1

각 단계의 색상을 너비로 변경하여 다각형의 외곽선을 다른 획 너비로 그립니다.

스 니펫은 한 가지 방법을 보여줍니다. 라인이 다각형을 그립니다은 "마이"와 "라운드"

"use strict"; 
 

 
const canvas = document.createElement("canvas"); 
 
canvas.height = innerHeight; 
 
canvas.width = innerWidth; 
 
canvas.style.position = "absolute"; 
 
canvas.style.top = canvas.style.left = "0px"; 
 
const ctx = canvas.getContext("2d"); 
 
document.body.appendChild(canvas); 
 

 
// poly to draw 
 
var poly = [0.1,0.2,0.4,0.5,0.2,0.8]; 
 
var poly1 = [0.6,0.1,0.9,0.5,0.8,0.9]; 
 

 
// convert rgb style colour to array 
 
function rgb2Array(rgb){ 
 
    var arr1 = rgb.split("(")[1].split(")")[0].split(","); 
 
    var arr = []; 
 
    while(arr1.length > 0){ 
 
     arr.push(Number(arr1.shift())); 
 
    } 
 
    return arr; 
 
} 
 
// convert array to rgb colour 
 
function array2rgb(arr){ 
 
    return "rgb("+Math.floor(arr[0])+","+Math.floor(arr[1])+","+Math.floor(arr[2])+")" 
 
} 
 

 
// lerps array from to. Amount is from 0 @ from 1 @ to. res = is the resulting array 
 
function lerpArr(from,to,amount,res){ 
 
    var i = 0; 
 
    if(res === undefined){ 
 
     res = []; 
 
    } 
 
    while(i < from.length){ 
 
     res[i] = (to[i]-from[i]) * amount + from[i];  
 
     i++; 
 
    } 
 
    return res; 
 
} 
 

 
// draw gradient outline 
 
// poly is the polygon verts 
 
// width is the outline width 
 
// fillStyle is the polygon fill style 
 
// rgb1 is the outer colour 
 
// rgb2 is the inner colour of the outline gradient 
 
function drawGradientOutline(poly,width,fillStyle,rgb1,rgb2){ 
 
    ctx.beginPath(); 
 
    var i = 0; 
 
    var w = canvas.width; 
 
    var h = canvas.height; 
 
    ctx.moveTo(poly[i++] * w,poly[i++] * h); 
 
    while(i < poly.length){ 
 
     ctx.lineTo(poly[i++] * w,poly[i++] * h); 
 
    } 
 
    ctx.closePath(); 
 
    var col1 = rgb2Array(rgb1); 
 
    var col2 = rgb2Array(rgb2); 
 
    
 
    i = width * 2; 
 
    var col = []; 
 
    while(i > 0){ 
 
     ctx.lineWidth = i; 
 
     ctx.strokeStyle = array2rgb(lerpArr(col1,col2,1- i/(width * 2),col)); 
 
     ctx.stroke(); 
 
     i -= 1; 
 
    } 
 
    ctx.fillStyle = fillStyle; 
 
    ctx.fill(); 
 
} 
 
ctx.clearRect(0,0,canvas.width,canvas.height) 
 
ctx.lineJoin = "miter"; 
 
drawGradientOutline(poly,20,"black","rgb(255,0,0)","rgb(255,255,0)") 
 
ctx.lineJoin = "round"; 
 
drawGradientOutline(poly1,20,"black","rgb(255,0,0)","rgb(255,255,0)")

합류
관련 문제