2017-02-08 7 views
1

こんにちは私はhtml5キャンバスを使用して株棒グラフを作成しようとすると、まず私はさまざまな方法でバーオブジェクトを作成することに決めましたが、それを動作させることはできません。HTML5キャンバスオブジェクト指向

<!DOCTYPE html> 
<html> 
<body> 

<canvas id="myCanvas" width="1024" height="600" style="border:3px solid #d3d3d3;"> 
Your browser does not support the HTML5 canvas tag.</canvas> 

<script> 
var context = document.getElementById("myCanvas").getContext("2d"); 


function Bar(time,open,high,low,close,dir){ 
    vertcord=time 
    openC=open 
    highC=high 
    lowC=low 
    closeC=close 
    line_width=8 
    bar_col='#ff0000' 

    if (dir==1){ 
    bar_col='#ace600' 
    } 

    this.moveTo(vertcord,highC); 
    this.lineTo(vertcord,lowC); 
    this.moveTo(vertcord-line_width/2,closeC); 
    this.lineTo(vertcord+30,closeC); 
    this.lineWidth = line_width 
    this.strokeStyle = bar_col; 
    this.stroke(); 


} 

for (i=0; i < 300; i++) { 
    tempShape = new Bar(450+i,0,200,100,150,1); 
    tempShape.drawToContext(context); 
} 

</script> 
</body> 
</html> 
+0

コンストラクタ関数で 'this'の代わりにキャンバスの[rendering context](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D)が必要です。 – Teemu

+0

Bar.drawToContext()は定義されていません。 –

+0

しかし、Barはオブジェクトでなければなりません。他の関数などで後で改善します。 – Riggun

答えて

0

function Bar(time,open,high,low,close,dir){ 
 
    this.vertcord = time; 
 
    this.openC = open; 
 
    this.highC = high; 
 
    this.lowC = low; 
 
    this.closeC = close; 
 
    this.line_width = 8; 
 
    this.bar_col = '#ff0000'; 
 

 
    if (dir ==1) { 
 
    \t this.bar_col = '#ace600'; 
 
    } 
 
\t \t 
 
    this.drawToContext = function(ctx) { 
 
\t ctx.moveTo(this.vertcord, this.highC); 
 
    \t ctx.lineTo(this.vertcord, this.lowC); 
 
    \t ctx.moveTo(this.vertcord-this.line_width/2,this.closeC); 
 
    \t ctx.lineTo(this.vertcord+30,this.closeC); 
 
    \t ctx.lineWidth = this.line_width 
 
    \t ctx.strokeStyle = this.bar_col; 
 
    \t ctx.stroke(); 
 
    } 
 
} 
 

 
var context = document.getElementById("myCanvas").getContext("2d"); 
 

 
for (i=0; i < 300; i++) { 
 
    tempShape = new Bar(450+i,0,200,100,150,1); 
 
    tempShape.drawToContext(context); 
 
}
<canvas id="myCanvas" width="1024" height="600" style="border:3px solid #d3d3d3;"> 
 
Your browser does not support the HTML5 canvas tag.</canvas>

私は、これはそれが適切に実装する方法、より良いa tutorialを読んbe.Youになってどのようにだと思う:生成されたバーオブジェクトはありません。これは私のコードである

を表示されませんJavaScriptのオブジェクト指向のパターン。 JavaScriptで「これ」の意味を理解してください。

+0

大変ありがとうございます。私はちょうどJSでOOPを学び始めたばかりです – Riggun

+0

数日間、各オブジェクトに独立した色をつけようとしましたが、オブジェクトをjwithoutループで作成してもtempShape1、tempShape2を作成して色を変えようとしても例えばtempShape1.bar_col = '#ace600'のような特定のシェイプは、すべてのシェイプの色を変更します。なぜそれが起こるのかわからないのは、形状の他のパラメータ:座標、変数などがうまく動作するからです。ポジションとフォームを変更するには問題ありません – Riggun

関連する問題