2011-10-16 39 views
1

我有一個我選擇以HTML呈現的大學項目,用戶將輸入三角形的三邊並將形狀呈現在屏幕上。我做了一個JavaScript代碼獲取這些值並創建x和y座標繪製三角形<canvas>標籤中:使用用戶輸入在SVG和HTML中繪製和繪製三角形

<script type="application/javascript"> 
function init() { 
var canvas = document.getElementById("canvas"); 
if (canvas.getContext) { 
var ctx = canvas.getContext("2d"); 
var a = *user input*; 
var b = *user input*; 
var c = *user input*; 
var ox = 450-(a/2); // 450px since the canvas size is 900px, 
var oy = 450+(y3/2); // this aligns the figure to the center 
var x3 = ((b*b)+(a*a)-(c*c))/(2*a); 
var y3 = Math.ceil(Math.sqrt((b*b)-(x3*2))); 
var img = new Image(); 
img.src = 'grad.png'; 
ctx.strokeStyle = '#fff'; 
ctx.lineWidth = 3; 
ctx.shadowOffsetX = 0; 
ctx.shadowOffsetY = 0; 
ctx.shadowBlur = 10; 
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; 
var ptrn = ctx.createPattern(img,'repeat'); 
ctx.fillStyle = ptrn; 
ctx.beginPath(); 
ctx.moveTo(ox,oy); 
ctx.lineTo(a+ox,oy); 
ctx.lineTo(ox+x3,oy-y3); 
ctx.lineTo(ox,oy); 
ctx.fill(); 
ctx.stroke(); 
ctx.closePath(); 
} 
} 
</script> 

<body onLoad="init();"> 
<canvas id="canvas" width="900" height="900"></canvas><br> 
</body> 

我試圖組成一個簡單的規模動畫一旦頁面加載使得三角形和其他形狀在屏幕上「增長」。如果我使用CSS,整個畫布將會縮放。另外,我不知道如何使這個動畫成爲可能,因爲這些值不是固定的,而是使用畫布,我不得不逐幀對這個動畫進行動畫處理。 現在,如果我使用CSS和SVG,我可以對每個元素使用簡單的易插入和縮放效果,問題是我必須使用用戶輸入的值在SVG中生成三角形。我怎樣才能做到這一點?

回答

0

如果你總是會在屏幕上有一個三角形(或多邊形),我會創建一個SVG/CSS的基本框架,並設置屬性wuth CSS:

<svg xmlns="http://www.w3.org/2000/svg" width="900" height="900"> 
    <defs> 
     <filter id="dropshadow" height="130%"> 
      <feGaussianBlur in="SourceAlpha" stdDeviation="10"/> 
      <feMerge> 
       <feMergeNode/> 
       <feMergeNode in="SourceGraphic"/> 
      </feMerge> 
     </filter> 
    </defs> 
    <polygon id="triangle" filter="url(#dropshadow)" /> 
</svg> 
<style> 
    #triangle { 
     fill: url(grad.png); 
     stroke-width: 3px; 
     stroke: white; 
    } 
</style> 

然後,您可以使用許多相同的代碼來設置多邊形點:

var points = [ 
    [ox, oy].join(','), 
    [a + ox, oy].join(','), 
    [ox + x3, oy - y3].join(',') 
    ].join(' '); 
document.getElementById('triangle').setAttribute('points', points); 

你可以在這裏看到一個例子:http://fiddle.jshell.net/fTPdy/

+0

謝謝!這正是我所期待的! – Samuel

2

三角形是一個3點的多邊形。看看SVG Polygon文檔。 在JavaScript中,你可以創建一個多邊形像這樣:

var svgns = "http://www.w3.org/2000/svg"; 

function makeTriangle() { 
    shape = svgDocument.createElementNS(svgns, "polygon"); 
    shape.setAttributeNS(null, "points", "5,5 45,45 5,45"); 
    shape.setAttributeNS(null, "fill", "none"); 
    shape.setAttributeNS(null, "stroke", "green"); 

    svgDocument.documentElement.appendChild(shape); 
}