How To Draw Power Curve In R
Firsthand drawing fashion vs path cartoon mode
Immediate Fashion = EXECUTING A CALL TO A Cartoon METHOD MEANS IMMEDIATELY Drawing IN THE Sheet
In the previous examples, we saw how to draw some rectangles using thefillRect(x, y, width, elevation)andstrokeRect(x, y, width, height) methods of the context.
Nosotros also learned how to depict a text message using thefillText(bulletin, 10, y) andstrokeText(bulletin, x, y) methods that draws a text in filled and wireframe mode, respectively.
These methods, along with thedrawImage(...) method already seen in section 3.3.iii, are"immediate methods": as soon as they are executed, the results are displayed on screen, the drawings are performed, pixels on the sheet area change their colors, etc.
Here is a code extract that volition draw 1000 random rectangles in a canvas, using immediate mode rectangle drawing calls.
- var sheet , ctx , w , h ;
- function init () {
- canvas = document . getElementById ( 'myCanvas' );
- ctx = canvas . getContext ( 'second' );
- westward = canvass . width ;
- h = canvass . height ;
- console . time ( "time to draw" );
- for ( var i = 0 ; i < 1000 ; i ++) {
- var 10 = Math . random () * w ;
- var y = Math . random () * h ;
- var width = Math . random () * w ;
- var height = Math . random () * h ;
- ctx . strokeRect ( x , y , width , elevation );
- }
- console . timeEnd ( "time to draw" );
- }
Lines 12-18 draw 1000 rectangles of random sizes in immediate mode. We too measure the time using the usualconsole.time(name_of_timer) andconsole.timeEnd(name_of_timer) that volition write in the browser panel the time elapsed. Note thatconsole.fourth dimension(...) andconsole.timeEnd(...) display results merely in the browser's panel, not in the JS Bin panel.
On a Mac Volume Pro from 2015, the outcome is:
PATH MODE = FILL A BUFFER THEN EXECUTE ALL BUFFERED ORDERS AT ONCE TO ENABLE OPTIMIZATION AND PARALLELISM
There is some other drawing mode called "path drawing mode" where you outset transport drawing orders to the graphics processor, and these orders are stored in a buffer. Then you call methods to describe the whole buffer at in one case. There are also methods to erase the buffer's content.
Path drawing mode allows parallelism: if you need to describe ten.000 rectangles, it's meliorate to store the orders in the graphics card, then execute the cartoon all at once, rather than doing x.000 firsthand calls tostrokeRect(...) for instance. With the buffered manner, the Graphic Processing Unit (GPU) of the graphics card hardware will be able to parallelize the computations (modern graphics cards can execute hundreds/thousands of things in parallel).
Extract from source code (the function that draws the rectangles):
- for ( var i = 0 ; i < 1000 ; i ++) {
- var ten = Math . random () * w ;
- var y = Math . random () * h ;
- var width = Math . random () * w ;
- var height = Math . random () * h ;
- ctx . rect ( x , y , width , height ); // shop a rectangle in path/buffer
- }
- ctx . stroke (); // draws the whole buffer (the 1000 rectangles) at once
Instead of callingstrokeRect(...) orfillRect(...), we just call therect(...) method of the context (line 7). This is how nosotros tin can delay the drawing of the rectangles. The 1000 rectangles are stored in a buffer in the hardware.
The call toctx.stroke() (line 9) or to its sister methodctx.make full() will draw the unabridged buffer contents in make full or stroke mode.
And here is what the timer gives: a slightly faster execution fourth dimension. Changing grand to 100.000 will give even larger differences.
Path style is faster than immediate manner!
RESET THE PATH Mode BUFFER
A call toctx.beginPath() will reset the buffer (empty its contents). Nosotros volition run into many more examples of using the Path drawing mode in some other section after on this week.
- // start a new buffer / path
- ctx . beginPath ();
- // all these orders are in a buffer/path
- ctx . moveTo ( 10 , 10 );
- ctx . lineTo ( 100 , 100 );
- ctx . lineTo ( 150 , 70 );
- // Draw the buffer
- ctx . stroke ();
SUMMARY OF PATH Way PRINCIPLES
- Call drawing methods that work in path mode, for instance telephone callctx.rect(...) instead ofctx.strokeRect(...) orctx.fillRect(...)
- Callctx.stroke() orctx.fill() to draw the buffer's contents,
- Beware that the buffer is never emptied, two sequent calls toctx.stroke() will draw the buffer contents twice! Instead, utilisectx.beginPath() to empty it if needed.
- It is possible to empty the buffer by callingctx.beginPath().
- Path drawing is faster than immediate drawing (parallelization is possible).
-
Path drawing: lines
INTRODUCTION
We have been drawing rectangles so far.
Permit's go a chip farther now past introducing the notion of "path cartoon". This approach consists in using thectx.moveTo(x, y) method of the context, in conjunction with other cartoon methods that end in "To", such asctx.lineTo(ten, y).
This makes cartoon multiple connected lines easier. Consecutive calls toctx.lineTo(x, y) volition store in the path/buffer a set up of connected lines that we will depict altogether by a unmarried call toctx.stroke() orctx.fill().
Hither are the unlike steps:
- Put the "pencil" somewhere with a call toctx.moveTo(x1, y1). This will be the origin of the beginning line.
- Call thectx.lineTo(x2, y2) method to draw a line from the previous position (previous pace) to the position passed as parameters to thelineTo(...) method. This position will serve as the origin for the next line to exist drawn.
- CalllineTo(x3, y3) again to draw a line that goes from (x2, y2) to (x3, y3). This line volition outset at the stop of the previous one.
- Repeat step iii to depict more than connected lines.
- Call thectx.stroke() or thectx.fill up() methods to draw the path defined past the different lines.
Note that the call toctx.stroke() orctx.fill() will employ the current values of thestrokeStyle orfillStyle properties. It is possible to callctx.moveTo(x, y) in the center of steps i through 5 in order to movement the pen somewhere else without connecting to the last fatigued line.
- var canvass = certificate . getElementById ( 'myCanvas' );
- var ctx = sail . getContext ( '2d' );
- // Vertical lines
- for ( var x = 0.5 ; 10 < 500 ; x += 10 ) {
- ctx . moveTo ( x , 0 );
- ctx . lineTo ( ten , 375 );
- }
- // Horizontal lines
- for ( var y = 0.v ; y < 375 ; y += 10 ) {
- ctx . moveTo ( 0 , y );
- ctx . lineTo ( 500 , y );
- }
- // Describe in blue
- ctx . strokeStyle = "#0000FF" ;
- // Before the execution of the next line zilch every bit been drawn yet !
- ctx . stroke ();
In this instance, the entire grid is fatigued during the execution of the terminal line of code, with the single call toctx.stroke().
Some other Example MIXING FILLED AND WIREFRAME SHAPES (AND Firsthand AND PATH MODES)
- var canvas = certificate . getElementById ( 'myCanvas' );
- var ctx = canvas . getContext ( '2d' );
- // a filled rectangle in immediate mode
- ctx . fillStyle = '#FF0000' ;
- ctx . fillRect ( 0 , 0 , lxxx , 100 );
- // ii sequent lines in path mode
- ctx . moveTo ( 0 , 0 );
- ctx . lineTo ( 100 , 100 );
- ctx . lineTo ( 100 , 0 );
- // draws only the two lines in wireframe mode
- ctx . strokeStyle = "#0000FF" ;
- ctx . stroke ();
This instance shows that filled and wireframe shapes should be drawn differently (here a filled rectangle is drawn using a telephone call to thefillRect(...) method while a wireframe set of connected lines is fatigued using thestroke() method of the context).
Drawing A Single PATH MADE WITH Disconnected LINES / PARTS
- var canvas = document . getElementById ( 'myCanvas' );
- var ctx = canvas . getContext ( '2d' );
- // first office of the path
- ctx . moveTo ( xx , 20 );
- ctx . lineTo ( 100 , 100 );
- ctx . lineTo ( 100 , 0 );
- // second role of the path, moveTo(...) is used to "jump" to another place
- ctx . moveTo ( 120 , twenty );
- ctx . lineTo ( 200 , 100 );
- ctx . lineTo ( 200 , 0 );
- // signal stroke color + depict the path
- ctx . strokeStyle = "#0000FF" ;
- ctx . stroke ();
In this case, we simply chosen themoveTo() method betwixt each part of the path. And we chosenstroke() merely once to draw the whole path.
Drawing lines with unlike styles
Mutual Error: DRAWING THE SAME PATH TWICE
Permit's look at the drawing from the last example of the previous section:
Imagine that we would similar to draw them with unlike styles and colors: the shape on the left will stay every bit it is now (bluish, wireframe), while the 2d shape on the right volition be filled, colored in pinkish. Permit's look at how we can do this...
Cartoon Two PATHS WITH Unlike STYLES, THE Wrong AND THE Skillful WAY!
Offset, the wrong mode!
In this instance, we volition describe the two parts of the path with different styles: the first role in wireframe way, and the second part in filled mode.
What nosotros will attempt first is to phone callstroke() after the first half of the path, and then callfill() subsequently the second half of the path (bank check this interactive example):
Here is the code:
- var canvas = document . getElementById ( 'myCanvas' );
- var ctx = sail . getContext ( '2d' );
- // commencement part of the path
- ctx . moveTo ( 20 , 20 );
- ctx . lineTo ( 100 , 100 );
- ctx . lineTo ( 100 , 0 );
- // indicate stroke colour + draw offset part of the path
- ctx . strokeStyle = "#0000FF" ;
- ctx . stroke ();
- // 2d part of the path
- ctx . moveTo ( 120 , twenty );
- ctx . lineTo ( 200 , 100 );
- ctx . lineTo ( 200 , 0 );
- // indicate stroke colour + draw the path
- ctx . fillStyle = "pink" ;
- ctx . fill ();
Hey - it does non work! Weirdly, the two parts of the path are filled in pink! Just we calledstroke() after the starting time half of the path was drawn (lines v-eight). Then we calledmake full() only after the 2nd role of the path was specified (lines 14-19)... and then, what happened?
Remember thatfill() orstroke() draws the whole path, fifty-fifty if it is disconnected, and even if it has already been drawn!
What happened is:
- The call to stroke() has drawn the path corresponding to the lines five-7. Indeed, the get-go part of the path (on the left) has actually been drawn once in wireframe mode, and in blueish.
- Then, the call tofill() at line 20 has drawn the whole path again, but in pink and in filled mode. But this time the path corresponds to lines 5-7 plus lines 14-16 that make upward the second shape on the correct. So the path that has been fatigued this time is fabricated of both of the triangles.
Important: If you do not want to draw parts of the same path several times, you need to draw two different paths, using thectx.beginPath() method, as shown in the next example.
At present, the right way!
Source code:
- var sheet = document . getElementById ( 'myCanvas' );
- var ctx = canvas . getContext ( 'second' );
- // get-go part of the path
- ctx . moveTo ( 20 , twenty );
- ctx . lineTo ( 100 , 100 );
- ctx . lineTo ( 100 , 0 );
- // indicate stroke colour + depict commencement part of the path
- ctx . strokeStyle = "#0000FF" ;
- ctx . stroke ();
- // start a new path, empty the electric current buffer
- ctx . beginPath ();
- // 2nd part of the path
- ctx . moveTo ( 120 , 20 );
- ctx . lineTo ( 200 , 100 );
- ctx . lineTo ( 200 , 0 );
- // point stroke colour + draw the path
- ctx . fillStyle = "pink" ;
- ctx . fill up ();
This time, in club to describe the two shapes differently, we defined two separate paths. The way to do this is just to callctx.beginPath() to start a new path. In this example, the first path has been drawn in wireframe style, so a new path has been started that is drawn in filled mode.
Drawing lines in immediate manner
Sometimes it might be useful to draw just 1 line without being in another path.
It'south interesting to encounter how we can write a single "describe line" function that takes the start and stop coordinates, the color, the line width, etc.
Here is the code:
- function drawLine ( x1 , y1 , x2 , y2 , color , width ) {
- ctx . save ();
- // fix color and lineWidth, if these parameters
- // are not divers, do nothing (default values)
- if ( color )
- ctx . strokeStyle = color ;
- if ( width )
- ctx . lineWidth = width ;
- // first a new path
- ctx . beginPath ();
- ctx . moveTo ( x1 , y1 );
- ctx . lineTo ( x2 , y2 );
- ctx . stroke ();
- ctx . restore ();
- }
Observe the save/restore of the context at the beginning/end of the function. This is Actually a expert practice to avoid affecting other functions' context.
- Line 13 starts a new path and then that the part will simply depict what it is meant to draw: a single line.
- Lines fifteen-17 move the "pen" at (x1, y1) then draw a line to (x2, y2), and the stroke at line 17 makes it announced on the screen.
- drawLine ( 0 , 0 , 100 , 100 );
- drawLine ( 0 , l , 150 , 200 , 'cherry-red' );
- drawLine ( 10 , 100 , 100 , 10 , 'green' , 10 );
Issue:
Practical instance: drawing arrows
In this department, nosotros present a function that draws arrows in a canvas, such as in the illustration below:
You might notice multiple implementations on the Spider web for drawing arrows in a canvass, but the one we are presenting has the reward of being rather simple and has the possibility to set the color and line width of the arrows.
Let'southward see some examples of use:
- // Adapted from : http://stackoverflow.com/questions/808826/depict-pointer-on-canvas-tag
- function drawArrow ( ctx , fromx , fromy , tox , toy , arrowWidth , color ){
- //variables to be used when creating the arrow
- var headlen = 10 ;
- var angle = Math . atan2 ( toy - fromy , tox - fromx );
- ctx . relieve ();
- ctx . strokeStyle = colour ;
- //starting path of the arrow from the start foursquare to the end square
- //and drawing the stroke
- ctx . beginPath ();
- ctx . moveTo ( fromx , fromy );
- ctx . lineTo ( tox , toy );
- ctx . lineWidth = arrowWidth ;
- ctx . stroke ();
- //starting a new path from the head of the pointer to one of the sides of
- //the point
- ctx . beginPath ();
- ctx . moveTo ( tox , toy );
- ctx . lineTo ( tox - headlen * Math . cos ( angle - Math . PI / 7 ),
- toy - headlen * Math . sin ( angle - Math . PI / 7 ));
- //path from the side point of the pointer, to the other side betoken
- ctx . lineTo ( tox - headlen * Math . cos ( angle + Math . PI / 7 ),
- toy - headlen * Math . sin ( angle + Math . PI / vii ));
- //path from the side indicate dorsum to the tip of the arrow, and so
- //once more to the opposite side point
- ctx . lineTo ( tox , toy );
- ctx . lineTo ( tox - headlen * Math . cos ( angle - Math . PI / 7 ),
- toy - headlen * Math . sin ( angle - Math . PI / vii ));
- //draws the paths created above
- ctx . stroke ();
- ctx . restore ();
- }
An arrow is made of ane line (the pointer torso) and three connected lines (the pointer head).
Equally we change some context properties in that function, we callrelieve() andrestore() at the beginning and at the stop of the function.
This function can exist improved in many means: adding shadows, using fill up() instead of stroke() , which gives strange results when the width is as well big, etc.
EXAMPLES
- drawArrow ( ctx , x , 10 , 100 , 100 , 10 , 'red' );
- drawArrow ( ctx , 100 , 10 , 140 , 140 , three , 'black' );
Consequence:
DRAW NICER ARROWS?
On the Web, you will detect many different ways to depict arrows.
This Web site is worth reading: http://www.dbp-consulting.com/tutorials/canvas/CanvasArrow.html. It details how to describe arrows with curved heads and different styles for the head. Note however that you lot will need to alter some parts if you desire it to support different line widths, etc.
Screenshot from a demo bachelor on the to a higher place Web site:
In a next part of the course dedicated to bend drawing in a sheet, we will likewise show how to describe curved arrows, with very simple code (much simpler than the one used for cartoon the clock's arrows above).
Closing a path
Thectx.closePath() method indicates that we would similar a airtight path: draw from the concluding point to the start one.
Source lawmaking:
- var canvas = document . getElementById ( 'myCanvas' );
- var ctx = canvas . getContext ( '2d' );
- // Path fabricated of iii points (defines ii lines)
- ctx . moveTo ( 20 , 20 );
- ctx . lineTo ( 100 , 100 );
- ctx . lineTo ( 100 , 0 );
- // Close the path, try commenting this line
- ctx . closePath ();
- // indicate stroke color + depict start part of the path
- ctx . strokeStyle = "blueish" ;
- ctx . stroke ();
- Lines 5-seven corresponds to a path made of two consecutive lines. If nosotros only callstroke() after that, two lines will be drawn on the canvas.
- Line 10 indicates that we would likea closed path. In that example, the call tostroke() atline 14 will depict the two lines plus an actress line that connects the last point of the path to the start one. It will describe a closed triangle!
Try commenting the line in the online example and meet the results!
Drawing circles and arcs
Thectx.arc(cx, cy, radius, startAngle, endAngle, drawInverse) method is useful for drawing arcs of circles. Information technology takes the heart of the circumvolve/arc, its radius, the starting angle of the arc (turning clockwise), the ending angle of the arc, and an optional parameter we volition talk about later.
TYPICAL USAGE
Typical usage for cartoon an arc/circle/ellipse is:
- ctx . arc ( centerX , centerY , radius , startAngle , endAngle ); // clockwise drawing
- ctx . arc ( centerX , centerY , radius , startAngle , endAngle , false );
The angles are in radians (between0 and2*Math.PI). The arc is fatigued clockwise. Beware that this may non seem natural if you're used to the trigonometric order.
The last parameter is optional and has a value offalse by default. Iftrue, instead of drawing an arc of circle that corresponds to the parameters, it will draw its complementary. See the examples below to encounter the departure.
EXAMPLE one: Cartoon AN ARC WITH RADIUS = 50, STARTING ANGLE = 0, END ANGLE = PI/ii
- ctx . beginPath ();
- // we ommited the last parameter
- ctx . arc ( 100 , 75 , 50 , 0 , Math . PI / 2 );
- ctx . lineWidth = x ;
- ctx . stroke ();
Here is the outcome:
If we alter the terminal parameter (we omitted information technology, and so it took a value offalse past default):
- ctx . beginPath ();
- // we ommited the last parameter
- ctx . arc ( 100 , 75 , 50 , 0 , Math . PI / 2,true );
- ctx . lineWidth = 10 ;
- ctx . stroke ();
And so, the outcome is the "complementary" of the previous arc:
Instance 2: DRAWING A FULL CIRCLE (FILLED + OUTLINED)
Source lawmaking:
- var canvas = document . getElementById ( "myCanvas" );
- var ctx = sail . getContext ( "2d" );
- var centerX = canvas . width / 2 ;
- var centerY = canvas . height / 2 ;
- var radius = 70 ;
- ctx . beginPath ();
- // Add to the path a total circle (from 0 to 2PI)
- ctx . arc ( centerX , centerY , radius , 0 , ii * Math . PI , false );
- // With path cartoon you lot tin can change the context
- // properties until a call to stroke() or fill up() is performed
- ctx . fillStyle = "lightBlue" ;
- // Draws the filled circle in lite bluish
- ctx . fill ();
- // Set for the outline
- ctx . lineWidth = 5 ;
- ctx . strokeStyle = "black" ;
- // draws Once again the path (the circumvolve), this
- // fourth dimension in wireframe
- ctx . stroke ();
- // Find we called ctx.arc() simply once ! And drew information technology twice
- // with different styles
Notice that we calledctx.arc() only one time! And drew it twice, with different styles, with calls toctx.stroke()andctx.fill(). Each call drew the divers path in wireframe and in filled mode!
PROPOSED PROJECTS
Project 1 - modify the previous example on http://jsbin.com/gazuba/2/edit in society to get:
Project two - make a modest program that draws a smiling head similar that (or brand something better!)
Cartoon rounded rectangles: thearcTo(x1, y1, x2, y2, radius) method
INTRODUCTION
There is another method calledctx.arcTo(x1, y1, x2, y2, radius), which is a bit complex to utilize, but very applied for drawing rounded rectangles.
TYPICAL Use
- ctx . moveTo ( x0 , y0 );
- ctx . arcTo ( x1 , y1 , x2 , y2 , radius );
This method can be confusing. It was divers mainly for cartoon rounded shapes like rounded rectangles. Nosotros used an excerpt here from the first-class tutorial on thearcTo(...) method available at http://www.dbp-consulting.com/tutorials/sail/CanvasArcTo.html.
It works like this:
- Describe an imaginary line through (x0,y0) and (x1,y1) , draw another imaginary line through (x1,y1) and (x2,y2),
- Have an imaginary circle of radiusr, and slide information technology upwards between the 2 lines until it just touches both lines. The two points at which the circle touches the lines are chosen the tangent points.
- arcTo(x1, y1, x2, y2, r) volition draw a line from the current point(x0,y0) to the offset tangent point on the line from(x0,y0) to(x1,y1),
- It volition likewise depict an arc from that tangent point to the other tangent point on the line from(x1,y1) to(x2,y2) along the circumference of the circle.
- Finally, it adds the tangent signal where the arc ends upwardly, on the line from(x1,y1) to(x2,y2) to the path as the new current bespeak on the path.
Case one: SIMPLE USE
- context . beginPath ();
- context . moveTo ( 0 , 20 );
- context . arcTo ( 100 , 100 , 200 , 20 , l );
- context . lineWidth = 5 ;
- context . strokeStyle = "#0000ff" ;
- context . stroke ();
EXAMPLE ii: DRAW A ROUNDED RECTANGLE
Source code:
- var roundedRect = office ( ctx , x , y , width , superlative , radius , fill , stroke ) {
- ctx . beginPath ();
- // draw top and superlative correct corner
- ctx . moveTo ( x + radius , y );
- ctx . arcTo ( 10 + width , y , 10 + width , y + radius , radius );
- // depict right side and lesser right corner
- ctx . arcTo ( x + width , y + pinnacle , x + width - radius , y + superlative , radius );
- // depict lesser and bottom left corner
- ctx . arcTo ( x , y + tiptop , x , y + summit - radius , radius );
- // describe left and pinnacle left corner
- ctx . arcTo ( ten , y , x + radius , y , radius );
- if ( make full ) {
- ctx . fill ();
- }
- if ( stroke ){
- ctx . stroke ();
- }
- }
- var canvass = certificate . getElementById ( 'myCanvas' );
- var ctx = canvas . getContext ( '2d' );
- ctx . strokeStyle = 'rgb(150,0,0)' ;
- ctx . fillStyle = 'rgb(0,150,0)' ;
- ctx . lineWidth = vii ;
- roundedRect ( ctx , xv , 15 , 160 , 120 , 20 , truthful , true );
In this example, each call toctx.arcTo(...) draws a side plus a corner. This makes united states of america suspect that thearcTo() method has been designed primarily for drawing rounded rectangles...
EXAMPLE 3 COMPARISON BETWEEN LINETO AND ARCTO
This example at JS Bin is the same as the previous one, except that we added at the terminate of the roundedRect function the same lines of code that depict the rounded rectangle, simply using lineTo instead of arcTo. Just requite it a await!
Quadratic curves
INTRODUCTION
Quadratic curves are defined by a starting point (chosen a "context point"), a control point, and an ending point. The bend fits the tangents betwixt the context and control points and betwixt the control and ending points.
The context point may be defined by a call to themoveTo(10, y) method of the context, or it may be the catastrophe point of a previous path, if nosotros're drawing a path made of several shapes. For case, drawing a line and a quadratic curve will brand the endpoint of the line the context bespeak for the quadratic curve.
The control point controls the curvature - if nosotros move the control point farther nosotros get a sharper curve.
TYPICAL USE
- context. moveTo ( contextX , contextY );
- context. quadraticCurveTo ( controlX , controlY , endX , endY );
- // Optional : set lineWidth and stroke color
- context. lineWidth = v ;
- context. strokeStyle = "#0000ff" ;
- // Draw!
- context. stroke ();
EXAMPLE 1: QUADRATIC Curve
Source code:
- var canvas = document . querySelector ( '#myCanvas1' );
- var context = canvas . getContext ( '2d' );
- context . beginPath ();
- context . moveTo ( 100 , 20 );
- context . quadraticCurveTo ( 230 , 200 , 250 , 20 );
- context . lineWidth = 5 ;
- context . strokeStyle = "#0000ff" ;
- context . stroke ();
We set a starting indicate in line 6:moveTo(...), then set the control and ending points with a call toquadraticCurve(...), at line 7, and so set up some backdrop for color, thickness, and finally we call thestroke() method for drawing the bend.
EXAMPLE ii: 50INES Connected WITH A QUADRATIC Curve
Source code:
- context . beginPath ();
- context . moveTo ( 100 , 20 );
- context . lineTo ( 200 , 80 );
- context . quadraticCurveTo ( 230 , 200 , 250 , 20 );
- context . lineTo ( 500 , xc );
- context . lineWidth = v ;
- context . strokeStyle = "#0000ff" ;
- context . stroke ();
Practical instance: use quadratics for drawing curved arrows
Nosotros suggest a useful function for drawing curved arrows. The code is a modified version of what has been proposed by several contributors to this thread at StackOverflow.
Source code of the role that draws a curved pointer:
- part drawCurvedArrow ( startPointX , startPointY ,
- endPointX , endPointY ,
- quadPointX , quadPointY ,
- lineWidth ,
- arrowWidth ,
- colour ) {
- // All-time Practice: the function changes color and lineWidth -> save context!
- ctx . salvage ();
- ctx . strokeStyle = color ;
- ctx . lineWidth = lineWidth ;
- // angle of the end tangeant, useful for drawing the arrow head
- var arrowAngle = Math . atan2 ( quadPointX - endPointX , quadPointY - endPointY ) + Math . PI ;
- // offset a new path
- ctx . beginPath ();
- // Torso of the arrow
- ctx . moveTo ( startPointX , startPointY );
- ctx . quadraticCurveTo ( quadPointX , quadPointY , endPointX , endPointY );
- // Caput of the arrow
- ctx . moveTo ( endPointX - ( arrowWidth * Math . sin ( arrowAngle - Math . PI / 6 )),
- endPointY - ( arrowWidth * Math . cos ( arrowAngle - Math . PI / half-dozen )));
- ctx . lineTo ( endPointX , endPointY );
- ctx . lineTo ( endPointX - ( arrowWidth * Math . sin ( arrowAngle + Math . PI / 6 )),
- endPointY - ( arrowWidth * Math . cos ( arrowAngle + Math . PI / 6 )));
- ctx . stroke ();
- ctx . closePath ();
- // BEST PRACTICE -> restore the context equally we saved information technology at the commencement
- // of the function
- ctx . restore ();
- }
This function takes equally parameters the start and cease points, the command betoken of the bend, the pointer width, the width of the arrow caput.
It computes the angle of the arrow at its endpoint (line 14) in lodge to compute the rotated endpoints of the ii lines of the arrow caput (lines 24 and 29).
Notice that once again, as we alter the context backdrop (color, lineWidth) in the body of the function, we save and restore the context at the beginning / end of the function.
Bezier curves
INTRODUCTION
Bezier curves are interesting generally for drawing "S" shapes or asymmetric curves.
Bezier curves are divers by a context point, similarly to quadratic curves, two control points that ascertain two tangents, and an catastrophe point.
The beginning part of the bend is tangential to the imaginary line divers by the context point and the offset command point. The second part of the curve is tangential to the imaginary line defined by the 2nd control bespeak and the ending point.
The all-time way to empathize how they work is to check out one of these interactive applications:
- http://blogs.sitepointstatic.com/examples/tech/canvass-curves/bezier-curve.html
- http://lib.ivank.net/?p=demos&d=bezier
- Prissy video tutorial: http://vimeo.com/106757336
TYPICAL USAGE OF BEZIER CURVES
Source lawmaking:
- ctx . moveTo ( contextX , contextY );
- context . bezierCurveTo ( controlX1 , controlY1 , controlX2 , controlY2 , endX , endY );
- // Optional : set lineWidth and stroke color
- context . lineWidth = 5 ;
- context . strokeStyle = "#0000ff" ;
- // Draw!
- ctx . stroke ();
EXAMPLE i
- context . beginPath ();
- context . moveTo ( 100 , 20 );
- context . bezierCurveTo ( 290 , - 40 , 200 , 200 , 400 , 100 );
- context . lineWidth = 5 ;
- context . strokeStyle = "#0000ff" ;
- context . stroke ();
EXAMPLE 2 WITH LINES, QUADRATIC, AND BEZIER CURVES IN A PATH
Extract from source lawmaking:
- context . beginPath ();
- context . moveTo ( 100 , 20 );
- context . lineTo ( 200 , 160 );
- context . quadraticCurveTo ( 230 , 200 , 250 , 120 );
- context . bezierCurveTo ( 290 , - forty , 300 , 200 , 400 , 150 );
- context . lineTo ( 500 , 90 );
- // TRY COMMENTING THIS LINE OUT
- context . closePath ();
- context . lineWidth = 5 ;
- context . strokeStyle = "#0000ff" ;
- context . stroke ();
In this example we use theclosePath() method to draw a line between the last path point and the first path point (line 11), so that the drawing looks like a pair of goggles.
Note how the dissimilar parts are linked together and brand a "path":
INTERESTING, INTERACTIVE TOOL FOR GENERATING CODE THAT DRAWS BEZIER CURVES
Screenshot:
Source: https://masf-html5.blogspot.com/2016/04/path-drawing-mode-lines-circles-arcs.html
Posted by: maxeyjact1957.blogspot.com
0 Response to "How To Draw Power Curve In R"
Post a Comment