Draw a Square Within a Circle Javascript
Creating and Drawing on an HTML5 Canvas using JavaScript
Let'due south explore what the canvas is and draw some shapes.
Prerequisites / Info
- This is role of the JS Game Dev Series
- You lot should have some cognition of JavaScript — I volition non explain irrelevant syntax such equally for-loops
- Knowledge of ES6 Classes is helpful just not required
- Basic math/geometry knowledge
- Bones creative skills
Starter Code
I moved this to a separate page to keep this article brusque and and then I but have to update it in 1 place.
Final Code for this Tutorial
You can get all the code from this tutorial on the repository below. Go on in mind there'south also a lot of code included that's not written here. This is considering I added more code to create screenshots/diagrams for this tutorial.
Note: Every bit the focus of this tutorial is non edifice a project, you don't need to copy every line exactly. In fact, since we'll be covering many examples, I encourage yous to play with it and brand a mess.
What is the Sail Element?
Some quick bullet points to introduce you to the canvas.
- Introduced with HTML version 5 to depict graphics using JavaScript
- Graphics can be 2d or 3D and information technology's able to use hardware acceleration
- Used frequently today for creating games and visualizations (information or artistic)
Steps to Getting Started with The Canvas
When working with a canvas there are five steps to get started.
- Create the canvas element — give it an id, and a width/pinnacle (HTML)
- Add base styles — middle the canvas, add a background color, etc (CSS)
- In JavaScript, get your sail element by using the id
- Use the canvas element to get the context (your toolbox; more on it later)
- Use the context to draw
We'll practice steps ane and two in HTML/CSS, but y'all could exercise it in JavaScript if yous prefer.
Steps one and two for this project
Our average / CodePen template already covered setting up the basic styles and adding a canvas element. For this project, I volition alter the canvas width/height to be 800x1200 to give us plenty of space.
// alphabetize.html
<sheet id="gameCanvas" width="800" tiptop="1200"></canvas>
I as well changed the canvas background to exist white and added some margin to the bottom.
// styles.css
body {
groundwork: #111;
colour: #f8f8f8;
} canvas {
background: #f8f8f8;
padding: 0;
margin: 0 auto;
margin-lesser: 1rem;
display: block;
}
Steps 3 and iv
Get the canvas element by id, then utilise information technology to go the "2d" context.
document.getElementById('gameCanvas')
— searches for an HTML element that has the id of gameCanvas
. Once it finds the chemical element, we tin and so dispense it with JavaScript.
canvas.getContext()
— context is our toolbox of paintbrushes and shapes. The 2D context contains the set of tools nosotros desire. If y'all were working with 3D, you would employ WebGL instead.
But wait what's with the function thingy wrapping all of this?
This is an immediately invoked office expression (IIFE). Nosotros use it to prevent our code from leaking out in the global telescopic. This has several benefits such as preventing players (if this were a game) from accessing your variables straight and prevents your lawmaking from colliding with someone else'southward code (such as a library or another script on the website). The semicolon is there in case some other code is loaded before ours and information technology doesn't take a semicolon at the end.
We'll talk more about security in a future commodity, for now, let's get to drawing stuff.
The Canvas Coordinate System
By default, the coordinate system starts at the acme left. (X: 0, Y: 0) Moving down or to the right increases Ten and Y positions. You tin can play with the instance below on this page.
Quiz: The Sail Element
- How practice you select the sheet element in JavaScript?
- How do you go the context?
- Where is X: 0, Y: 0 on the canvas by default?
Uncomplicated Shapes
Let's make use of the 2d context object to draw shapes. Feel free to reference the documentation page at whatsoever time.
There will besides be a link to each method we use.
Just wait for the DOM…
Before we describe annihilation, we want to make sure the DOM (HTML) finished loading to avoid whatever related errors. To do that, nosotros will make a function to handle the setup process nosotros did to a higher place and mind for the DOMContentLoaded
upshot. We volition telephone call this function init
(for initialize).
Remember: everything stays inside the IIFE wrapper. I won't be showing it in the example code from at present on. If you ever get lost refer to the completed projection here .
Nosotros want our canvas and context variables to be available to all of our functions. This requires defining them upwardly superlative and so giving them a value in the init
function once the DOM loads. This completes our setup.
Annotation: A more scalable selection is to take the context variable as an argument to our drawing functions.
Rectangles / Squares 🔲
Permit'southward start past creating a foursquare:
Inside of our init
function, we use context2D.beginPath
to tell the sail nosotros want to commencement a new path/shape. On the adjacent line, we create and depict a rectangle (a square in this case).
In that location are two unlike methods we use to draw the path to the screen:
ctx.strokeRect(x, y, width, elevation)
— this creates a "stroked" rectangle. Stroke is the aforementioned thing as an outline or border
ctx.fillRect(x, y, width, summit)
— like to strokeRect
just this fills in the rectangle with a color
The Effect:
At that place are a few things to note hither:
- The colors default to blackness stroke and black fill.
- The origin point or 10: 0, Y: 0 for these shapes are at their summit left, similar to the sheet.
- I merely picked a random x, y for the first square and then added 50 + 50+ 25 (previous square X + previous square width + 25px margin) for the x position.
What if we want to change the colour/style? Let's add a crimson outlined foursquare that's too filled with bluish.
Position first:
- 10 = 200 previous foursquare width + previous position + 25px margin = l + 125 + 25
- Y = 35 We volition go on it in the same row
- The size volition be the same (fifty 10 50)
ctx.beginPath()
ctx.strokeRect(200, 35, 50, 50) // plugging in our new position
Just expect… we want a fill AND a stroke, does this mean we have to draw two squares? Yous can draw two squares but we will make use of several other methods instead.
The Result:
ctx.rect(10, y, width, summit)
— this is like the other two rectangle methods, only it does not immediately draw information technology. It creates a path for the square in memory, nosotros and so configure the stroke, fill, and stroke width before calling ctx.make full
and/or ctx.stroke
to draw it on screen
ctx.strokeStyle = 'whatsoever valid css colour'
— sets the outline/stroke colour to any string that works in CSS. i.east. 'blue', 'rgba(200, 200, 150, 0.5)', etc
ctx.fillStyle = 'any valid css color'
— same as above but for the fill
ctx.lineWidth = number
— sets the stroke width
ctx.make full()
— fills the current path
ctx.stroke()
— strokes the electric current path
Drawing any shape always follows these steps:
- Set the styles — optional and tin can be fix any time earlier rendering
- Brainstorm the path — outset creating the virtual path (not drawn to screen yet)
- Use the path functions to create a shape — i.e. the
rect
method - Depict the path to the screen — using fill or stroke
Note: We did non need to use the
ctx.rect()
function just to change the colors, nosotros used it because nosotros wanted both a stroke and a fill. You can just as easily setctx.fillStyle
and employctx.fillRect()
Setting the fill or stroke style will cause any shapes created afterward, to have the same style. For example, if we add a fourth square using the lawmaking below it would have the same style equally the third square.
// 4th square, uses the same way defined previously
ctx.beginPath()
ctx.rect(275, 35, l, 50)
ctx.fill up()
ctx.stroke()
Issue:
Anytime you desire to add a fill/stroke to your shapes, explicitly define the styles.
Optimizing our Code with Classes
Making apply of classes nosotros can create a robust Rectangle object and clean upwardly our code.
Classes are functions that create Objects. We want to create Rectangle objects that contain information about themselves, such as their position, styles, area, and dimensions.
I won't go into much particular on classes as it's non required and you can get by with normal functions. Check the MDN documentation page on classes to learn more most them.
Classes are optional and if the syntax confuses you, then just think of it as an object with methods and properties. Classes aside, two more sail functions were introduced in the draw method:
ctx.save()
— saves the current styles
ctx.restore()
— restores the terminal saved styles
We use these methods to forbid the issue nosotros saw with the fourth foursquare that had unexpected colors.
Canvass stores styles on a stack structure. When we call ctx.save()
it pushes the current styles onto the stack and calling ctx.restore()
pops it off the stack.
I only saved one set of styles in this animation but yous tin can save equally many times as you want and restore the nearly contempo styles. Note that saving does not reset the current styles.
Styles include:
strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, management, imageSmoothingEnabled
— MDN
We tin can now offset putting this Rectangle course to use:
The Effect:
Annotation: I added a grid for the screenshots. We'll be making a filigree at the end of this section.
Nosotros can keep reusing the grade to make more squares/rectangles:
We create an array and populate information technology with new Rectangles positioned based on the mySquare
object created before. Then we loop over the array and call the describe method on every square.
What exercise we get from all that code?
Well… it's something.
I know this is all boring and tedious but nosotros've covered the basics of canvas and you've at least seen what a class looks like now. Let's finish creating more shapes. (it'll go quicker from at present on I promise)
Lines 🔗
Rectangles are the but pre-defined shape with canvas, we create other shapes on our own. We tin use lines to build the foundation of these shapes.
The Issue:
New Methods:
ctx.moveTo(x, y)
— you can think of this as moving our virtual "pen", we use it to ready the starting point for the first line
ctx.lineTo(x, y)
— creates a line to X, Y; the starting signal is the last position of our "pen". This allows us to get-go new lines at the endpoint of previous lines.
ctx.closePath()
— when using a stroke we demand to call this to draw the final line and close the path. Fill volition automatically close the path
Note: If you need curved lines and so y'all can use Bézier curves with the quadratic or cubic bézier curve functions. I'll embrace them in another tutorial to keep this one from becoming too long.
Text 🔤
If y'all ever worked with any kind of text editor like to Microsoft Word or whatsoever of Adobe'south tools, and then these options will be familiar to you lot.
ctx.strokeText(text, x, y)
— creates the text path and strokes it
ctx.fillText(text, x, y)
— same as above simply fills the text
ctx.font(CSSFontString)
— ready the font using the CSS font format
ctx.measureText(text)
— performs some calculations using the current styles and returns an object with the results, including the calculated width
The rest of the options are self-explanatory or require knowledge of font blueprint, which is exterior the scope of this tutorial.
- ctx.textAlign
- ctx.textBaseline
Circles & Partial Circles (arcs) 🔴
The just new part here is the arc
method.
arc(10, y, radius, startAngle, endAngle, antiClockwise)
X, Y
— defines the position of the center point, not the peak left
radius
— the size of the circle/arc
startAngle, endAngle
— I call up these are self-explanatory only information technology's important to note that these angles are in Radians not degrees.
Math Aside: 1Ï€ (Pi) radians is equal to half a circle, 2Ï€ gives you a total circle.
Sentinel this video for more on the math of a circle
Triangles 🔺
As there are no triangle functions, nosotros accept to make them ourselves using lines.
Cypher new here. Refer to the sections to a higher place if you're lost. (or inquire in the comments)
Quiz: Basic Shapes
- What arguments does the
rect(_, _, _, _)
function take? - After yous've used the
rect
function, what two methods can draw the rectangle to the screen? (the same functions for whatsoever path) - What function can create circles?
- What two properties tin we set to change the fill and outline styles?
- How exercise yous ready the starting position when using
lineTo(ten,y)
Answers: (links to related MDN pages)
- Rect office docs
- Drawing method 1, drawing method 2
- Function to describe circles
- strokeStyle, fillStyle
- ctx.moveTo(x,y)
Challenge: Visualize the Canvass Coordinate System
Use what you learned to depict a coordinate plane or filigree with X and Y starting at the top left and terminate where the canvas ends.
Examples
Tips
- Use for loops to create multiple lines
- Information technology can be a full filigree, only text, or lines with tick marks... Make the grid yous will want to utilise
- As we haven't covered blitheness yet, don't worry most animating it. The example above was animated only for demonstration purposes.
Solution
Don't worry if y'all didn't solve it, this i is challenging.
I started by making a new JS file and loading it instead of the instance shapes from earlier.
<!-- index.html --> <!-- <script src="js/index.js"></script> --> <script src="js/gridSolution.js"></script>
Add the initial setup to your new JS file.
Now, decide if y'all desire to make a reusable Grid class or create something simpler. I volition keep it elementary for this example solution by using simply one office.
Wait at the to a higher place code, then try to fill in the blanks yourself if y'all haven't already solved it. The side by side snippet will exist the complete lawmaking.
Experience complimentary to tweak your grid and relieve it for time to come employ. I saved the animated i as an NPM parcel to employ with upcoming tutorials.
Terminal Challenge: Depict Some Art
Now information technology's time to put everything you've learned to use, here'due south your challenge:
Draw a motion picture using a combination of the shapes we learned.
Find some reference images or make something up.
Ideas
- Emojis / Faces
- Flags (Japan'due south flag? 😂)
- 2D Game/Cartoon Characters
- Logos
- Charts (bar nautical chart, pie chart, etc) — a little more than advanced and I'll exist doing another tutorial on charts but if you desire to effort it on your own go for it.
- Landscape — depict a business firm, some grass, a sun or perhaps a starry nighttime sky
- Search for examples on CodePen to get ideas (set up to be overwhelmed by the crazy fine art some people make)
Tips
- Apply
canvas.height / 2
andcanvas.width / ii
to get the center X, Y of the canvas - If y'all did the grid challenge from earlier, now is a good time to use it
- If your drawing needs a lot of curves, wait into the bezier curve functions: quadraticCurveTo and bezierCurveTo
- Effort finding some examples on CodePen
- Keep it simple. This challenge is just to exercise cartoon shapes on the sheet, non to create some complex game grapheme.
When you cease share a link to your CodePen / GitHub repository in the comments.
Reflection
What did y'all struggle with the near? Or was everything a cakewalk? What could have been different? I would honey to hear your feedback in the comments. Otherwise, note what you lot struggled with and spend more than time researching and reviewing that topic.
Resources and Links
Dorsum to Alphabetize Folio
Thanks for Reading!
I had to cut a lot of information to continue this tutorial from getting too long but nosotros'll be roofing pretty much everything throughout the series.
I would love to hear your feedback and questions! Get out a annotate beneath or message me on Twitter.
Source: https://codeburst.io/creating-and-drawing-on-an-html5-canvas-using-javascript-93da75f001c1
0 Response to "Draw a Square Within a Circle Javascript"
Post a Comment