2012-04-10 30 views
2

円と三角形を描画する2つの関数を定義しました。非常にストレートなもの。キャンバスアイテムが適切にレンダリングされない

function circle(offset, size){ 
    var color = $("#color option:selected").val(); 
    var canvas = document.getElementById("canvas"); 
    var context = canvas.getContext("2d"); 
    radius = size * 1; 

    context.beginPath(); 
    context.arc(offset, 2, radius, 0, 2 * Math.PI, false); 
    context.fillStyle = color; 
    context.fill(); 
} 

function triangle(offset, size){ 
    var color = $("#color option:selected").val(); 
    var canvas = document.getElementById("canvas"); 
    var context = canvas.getContext("2d"); 
    var width = size * 6; 
    var height = size * 5; 
    var padding = 0; 

    // Draw a path 
    context.beginPath(); 
    context.moveTo(offset + width/2, padding); 
    context.lineTo(offset + width, height + padding); 
    context.lineTo(offset, height + padding); 
    context.closePath(); 

    // Fill the path 
    context.fillStyle = color; 
    context.fill(); 
} 

私は私のページにキャンバスを追加した午前:私はサークルを見て、正しくレンダリングません方形することができますいくつかの理由で

<canvas id="canvas"></canvas> 

。添付のスクリーンショットを参照してください。

enter image description here

enter image description here

答えて

6

私はほとんどあなたがCSSの幅と高さではなく<canvas> HTML属性を使用してキャンバスの幅と高さを設定しているので、それがあることを保証することができます。

次のいずれかのキャンバスタグの幅/高さを定義する必要があります:<canvas width="500" height="500">

またはコードで:CSSによる

var canvas = document.getElementById("canvas"); 
canvas.width = 500; 
canvas.height = 500; 

とされていません。あなたはこれをしなかった場合:

<canvas style="width: 500px; height: 500px;">

は、その後、あなたは/スケールほぼ確実にあなたが取得しているものである500×500であることが反った300x150のキャンバス(デフォルトサイズ)を持っています。

(私は上記のフリーハンドを書いているので、タイプミスがあるかもしれませんが、アイデアを得ます)

+0

私はそれをと完全に動作します。ありがとう! – Tithos

関連する問題