Reputation: 10095
I'm new to HTML5 and JavaScript. I'm working on a very simple 'canvas' project where you have two test tubes and clicking on one reduces its level and increases the level of the other.
I've written code to do this and it works, the only trouble is that when I click on the test tube - it moves diagonally across the screen and I don't know what's causing it.
It'd be great if you could go through the code and tell me where the problem is:
TestTube.js
TestTube.prototype.render = function(){
this.graphics.clear();
this.graphics.setStrokeStyle(2,1,1);
//set stroke color black.
this.graphics.beginStroke("#000000");
//set fill color
this.graphics.beginFill(this.color);
//START DRAWING------------------------------------
//move to origin.
this.graphics.moveTo(this.x,this.y);
//draw line down to point of liquid in test tube [liquid start point]
_level = (100 - this.level)/100;
this.graphics.lineTo(this.x,this.y+_level*this.height);
//draw line uptil bottom of test tube.
this.graphics.lineTo(this.x,this.y+(this.height-this.width/2));
//draw the round part of test tube.
//graphics.arc(centerX,centerY,radius,startAngle,endAngle,anticlockwise);
this.graphics.arc(this.x + this.width/2,this.y+(this.height-this.width/2),this.width/2,Math.PI,0,true);
//go back to upto level of liquid in tube [liquid end point]
this.graphics.lineTo(this.x+this.width,this.y+_level*this.height);
//connect liquid start point with liquid end point to fill in liquid colour.
this.graphics.lineTo(this.x,this.y+_level*this.height);
this.graphics.endFill();
//go back to liquid end point
this.graphics.moveTo(this.x+this.width,this.y+_level*this.height);
//draw the rest of the test tube.
this.graphics.lineTo(this.x+this.width,this.y);
//stop drawing.
this.graphics.endStroke();
}
index.js
chemical.addEventListener('click',function(e){
e.target.level--;
e.target.render();
solution.level++;
solution.render();
stage.update();
});
Upvotes: 0
Views: 160
Reputation: 24548
It is because you first move to (x, y):
this.graphics.moveTo(this.x,this.y);
And then add (x, y) again to your draw calls:
this.graphics.lineTo(this.x,this.y+(this.height-this.width/2)); // etc
You only want to add (x, y) once.
Upvotes: 1