HTML and CSS Reference
In-Depth Information
ctx.moveTo(this.bx,this.by);
ctx.lineTo(this.s1x,this.s1y);
ctx.moveTo(this.bx,this.by);
ctx.lineTo(this.s2x,this.s2y);
ctx.moveTo(this.s1x,this.s1y);
ctx.lineTo(this.s2x,this.s2y);
ctx.lineTo(this.s3x,this.s3y);
ctx.stroke();
}
It does the following:
adds to path a line from bx,by to s1x,s1y
adds to path a line from bx,by to s2x,s2y
adds to path a line from s1x,s1y to s2x,s2y
adds to path a line from s2x,s2y to s3x,s3y
As always, the way to learn this is to experiment with your own designs. If theres no invocation of moveTo ,
the next lineTo draws from the destination of the last lineTo . Think of holding a pen in your hand and
either moving it on the paper or lifting it up and moving without drawing anything. You also can connect
arcs. Chapter 5 demonstrates drawing polygons.
Mouse events for pulling on the slingshot
The slingshot application replaces form input with mouse drag and drop operations. This is appealing
because its closer to the physical act of pulling back on a slingshot.
When the player presses down on the mouse button, it is the first of a sequence of events to be managed
by the program. Here is pseudo-code for what needs to be done.
When the player presses the mouse button, check if the mouse is on top of the ball. If not, do
nothing. If so, set a variable named inmotion.
If the mouse is moving, check inmotion. If it is set, move the ball and the strings of the slingshot.
Keep doing this until the mouse button is released.
When the player releases the mouse button, reset inmotion to false. Calculate the angle and initial
velocity of the ball and from these calculate the horizontal velocity and the initial vertical velocity.
Start the ball moving.
You can use HTML5 and JavaScript to set up event handling for pressing the standard (left) mouse
button, moving the mouse, and releasing the mouse button. The code uses a method based on the canvas
element directly, not the so-called context. Here is the code, which is in the init function:
canvas1 = document.getElementById('canvas');
canvas1.addEventListener('mousedown',findball,false);
canvas1.addEventListener('mousemove',moveit,false);
canvas1.addEventListener('mouseup',finish,false);
Now because this event is in terms of the whole canvas, the findball function must determine if the
mouse is over the ball. The first task is to get the mouse x and y coordinates. Unfortunately, different
browsers implement mouse events in different ways. The following works for Firefox, Chrome, and Safari.
 
Search WWH ::




Custom Search