HTML5 Canvas面向对象

时间:2017-02-08 07:35:35

标签: javascript html html5 canvas

您好我试图使用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>

1 个答案:

答案 0 :(得分: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 ) {
    	this.bar_col = '#ace600';
    }
		
    this.drawToContext = function(ctx) { 
	ctx.moveTo(this.vertcord, this.highC);
  	ctx.lineTo(this.vertcord, this.lowC);
   	ctx.moveTo(this.vertcord-this.line_width/2,this.closeC);
    	ctx.lineTo(this.vertcord+30,this.closeC);
    	ctx.lineWidth = this.line_width
    	ctx.strokeStyle = this.bar_col;
    	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如何在JavaScript中正确实现面向对象的模式。并了解JavaScript中“this”的含义。

相关问题