2012-05-04 58 views
0

我想沿着一組點繪製使用HTML5畫布的管道/管道。我嘗試繪製漸變線,以便它看起來像一個管道,彎道上的漸變不是連續的。使用HTML5畫布繪製管道/管道

將合成操作設置爲異或時,它有點不錯,但不是很好。

var MIDDILE_COLOR = "#ffffff"; 
 
var LINE_WIDTH = 20; 
 
window.onload = function() { 
 
    try { 
 
    var context = document.getElementById("abc").getContext("2d"); 
 
    var points = [ 
 
     [90, 136], 
 
     [101, 21], 
 
     [101, 21], 
 
     [376, 133], 
 
     [100, 300] 
 
    ]; 
 
    drawConnectionPipe(context, points, 10, "#ff0000"); 
 
    } catch (e) { 
 
    alert(e); 
 
    } 
 

 
} 
 

 
function drawConnectionPipe(ctx, coorinateArray, thickness, gradColor) { 
 
    try { 
 

 
    ctx.save(); 
 

 
    var gradientObject = null; 
 
    //ctx.globalCompositeOperation = 'xor'; 
 
    for (var i = 0; i < coorinateArray.length - 1; i++) { 
 
     var startPt = coorinateArray[i]; 
 
     var endPt = coorinateArray[i + 1]; 
 

 
     var arr = getPerpendicularPoints(startPt[0], startPt[1], endPt[0], endPt[1]); 
 
     gradientObject = ctx.createLinearGradient(arr[0], arr[1], arr[2], arr[3]); 
 

 
     gradientObject.addColorStop(0, gradColor); 
 
     gradientObject.addColorStop(0.5, MIDDILE_COLOR); 
 
     gradientObject.addColorStop(1, gradColor); 
 
     ctx.lineWidth = thickness; 
 
     ctx.strokeStyle = gradientObject; 
 
     ctx.lineJoin = "round"; 
 

 
     ctx.beginPath(); 
 
     ctx.moveTo(startPt[0], startPt[1]); 
 
     ctx.lineTo(endPt[0], endPt[1]); 
 
     ctx.closePath(); 
 
     ctx.stroke(); 
 

 

 
     //ctx.globalCompositeOperation = 'source-over'; 
 

 
    } 
 

 
    ctx.restore(); 
 
    } catch (e) { 
 
    alert(e); 
 
    } 
 
} 
 

 
function getPerpendicularPoints(x1, y1, x2, y2) { 
 
    var slantAngle = 0; 
 
    var slant = (x1 - y1)/(x2 - y2); 
 
    slantAngle = Math.PI/2 - Math.atan2(y2 - y1, x2 - x1); 
 
    var originX = (x1 + x2)/2; 
 
    var originY = (y1 + y2)/2; 
 

 
    var halfDistance = LINE_WIDTH/2; 
 

 
    var perpX1 = originX + halfDistance * Math.sin(90 * Math.PI/180 - slantAngle); 
 
    var perpY1 = originY + halfDistance * -Math.cos(90 * Math.PI/180 - slantAngle); 
 

 
    var perpX2 = originX + halfDistance * Math.sin(270 * Math.PI/180 - slantAngle); 
 
    var perpY2 = originY + halfDistance * -Math.cos(270 * Math.PI/180 - slantAngle); 
 

 
    return [perpX1, perpY1, perpX2, perpY2]; 
 

 
} 
 

 
function getNormalizedAtan2(ydiff, xdiff) { 
 
    var atan2Res = Math.atan2(ydiff, xdiff); 
 
    if (atan2Res < 0) { 
 
    atan2Res += (2 * Math.PI) 
 
    } 
 

 
    return atan2Res; 
 
}
<html> 
 

 
<head> 
 
    <title>Raphael Play</title> 
 
</head> 
 

 
<body> 
 

 
    <canvas id="abc" width="500" height="500"></canvas> 
 

 
</body> 
 

 
</html>

回答

1

最後我實現它使用svg filters。在html5畫布中,創建這種照明非常困難。

+0

您可以請一個小提琴,plunkr或codepen來說明您的解決方案嗎?我正在嘗試做同樣的事情。謝謝。 – junerockwell