banner



How To Draw Squares In Convas C# Wpf

Let's explore what the sail is and draw some shapes.

Prerequisites / Info

  • This is part of the JS Game Dev Series
  • You should accept some knowledge of JavaScript — I will non explain irrelevant syntax such as for-loops
  • Cognition of ES6 Classes is helpful but non required
  • Basic math/geometry knowledge
  • Basic artistic skills

Starter Code

I moved this to a carve up folio to go along this article short and so I only have to update information technology in one place.

Final Code for this Tutorial

Y'all can get all the lawmaking from this tutorial on the repository beneath. Go along in mind there's as well a lot of code included that's not written hither. This is because I added more than code to create screenshots/diagrams for this tutorial.

Note: As the focus of this tutorial is not building a project, you don't demand to copy every line exactly. In fact, since nosotros'll be covering many examples, I encourage you to play with it and brand a mess.

What is the Canvas Chemical element?

Some quick bullet points to innovate y'all to the canvas.

  • Introduced with HTML version five to draw graphics using JavaScript
  • Graphics can be 2D or 3D and it's able to utilize hardware acceleration
  • Used frequently today for creating games and visualizations (information or creative)

Steps to Getting Started with The Canvas

When working with a canvas there are five steps to get started.

  1. Create the canvas element give information technology an id, and a width/height (HTML)
  2. Add base styles — heart the canvas, add a background color, etc (CSS)
  3. In JavaScript, get your canvas element past using the id
  4. Employ the canvas element to get the context (your toolbox; more on it subsequently)
  5. Utilize the context to depict

We'll do steps one and 2 in HTML/CSS, just you lot could do information technology in JavaScript if you adopt.

Steps 1 and 2 for this project
Our average / CodePen template already covered setting up the basic styles and adding a canvas element. For this projection, I will change the canvass width/height to be 800x1200 to give us plenty of space.

          // alphabetize.html
<canvas id="gameCanvas" width="800" height="1200"></canvas>

I also inverse the canvas background to be white and added some margin to the lesser.

          // styles.css
trunk {
background: #111;
color: #f8f8f8;
}
canvas {
background: #f8f8f8;
padding: 0;
margin: 0 automobile;
margin-bottom: 1rem;
brandish: block;
}

Steps 3 and four
Get the canvas element by id, then use it to get the "second" context.

grab the canvas chemical element and create a 2d context

document.getElementById('gameCanvas') — searches for an HTML element that has the id of gameCanvas. Once it finds the element, we can then manipulate it with JavaScript.

sheet.getContext() — context is our toolbox of paintbrushes and shapes. The 2nd context contains the set of tools we want. If yous were working with 3D, you lot would utilise WebGL instead.

Simply wait what's with the function thingy wrapping all of this?

This is an immediately invoked function expression (IIFE). We utilise it to prevent our code from leaking out in the global scope. This has several benefits such as preventing players (if this were a game) from accessing your variables directly and prevents your code from colliding with someone else's code (such as a library or another script on the website). The semicolon is in that location in case some other code is loaded earlier ours and it doesn't have a semicolon at the end.

We'll talk more about security in a hereafter commodity, for at present, let's go to drawing stuff.

The Canvas Coordinate System

By default, the coordinate system starts at the top left. (X: 0, Y: 0) Moving down or to the right increases X and Y positions. You can play with the example below on this page.

a grid/coordinate projection nosotros'll be creating

Quiz: The Canvas Element

  1. How do y'all select the sail element in JavaScript?
  2. How do you become the context?
  3. Where is X: 0, Y: 0 on the sail past default?

Simple Shapes

Let's make use of the 2nd context object to draw shapes. Experience complimentary to reference the documentation page at any time.

There will also be a link to each method we use.

But wait for the DOM…

Before we draw anything, 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 we did above and listen for the DOMContentLoaded event. Nosotros will call this role init (for initialize).

Remember: everything stays inside the IIFE wrapper. I won't be showing it in the case lawmaking from now on. If you ever go lost refer to the completed project hither .

wait for DOM to load then run init function

We want our canvas and context variables to be bachelor to all of our functions. This requires defining them up top and and so giving them a value in the init part once the DOM loads. This completes our setup.

Note: A more scalable option is to accept the context variable as an argument to our drawing functions.

Rectangles / Squares 🔲

Let's commencement past creating a square:

basic *squares*

Within of our init function, we use context2D.beginPath to tell the canvas we want to kickoff a new path/shape. On the next line, we create and draw a rectangle (a square in this case).

There are two different methods we use to depict the path to the screen:

ctx.strokeRect(x, y, width, height) — this creates a "stroked" rectangle. Stroke is the same thing every bit an outline or edge

ctx.fillRect(x, y, width, tiptop) — similar to strokeRect but this fills in the rectangle with a colour

The Result:

stroked square and filled square

There are a few things to note hither:

  1. The colors default to blackness stroke and blackness make full.
  2. The origin point or X: 0, Y: 0 for these shapes are at their top left, similar to the sheet.
  3. I but picked a random x, y for the first square then added 50 + fifty+ 25 (previous square X + previous square width + 25px margin) for the x position.

positioning the squares

What if we want to change the color/style? Let's add a crimson outlined square that'southward also filled with blue.

Position outset:

  • Ten = 200 previous square width + previous position + 25px margin = 50 + 125 + 25
  • Y = 35 We volition keep it in the same row
  • The size will be the same (l x 50)
          ctx.beginPath()
ctx.strokeRect(200, 35, 50, l) // plugging in our new position

Only wait… we want a fill up AND a stroke, does this mean we have to describe two squares? You can draw two squares merely we will make use of several other methods instead.

create an outline and filled in square

The Result:

a third colorful foursquare

ctx.rect(10, y, width, height) — this is like the other two rectangle methods, but it does not immediately draw it. It creates a path for the square in memory, we then configure the stroke, fill, and stroke width before calling ctx.fill and/or ctx.stroke to draw information technology on screen

ctx.strokeStyle = 'whatever valid css color' — sets the outline/stroke color to whatsoever cord that works in CSS. i.e. '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.fill() — fills the current path

ctx.stroke() — strokes the current path

Cartoon any shape e'er follows these steps:

  1. Set the styles — optional and tin be set any time before rendering
  2. Begin the path — start creating the virtual path (non fatigued to screen nevertheless)
  3. Use the path functions to create a shape — i.e. the rect method
  4. Describe the path to the screen — using fill or stroke

Note: We did not need to apply the ctx.rect() part just to change the colors, we used it considering we wanted both a stroke and a fill. You lot tin just as hands set ctx.fillStyle and use ctx.fillRect()

Setting the make full or stroke style will cause any shapes created later, to have the aforementioned style. For example, if we add together a fourth square using the lawmaking beneath information technology would have the same mode as the tertiary square.

          // fourth square, uses the same style defined previously
ctx.beginPath()
ctx.rect(275, 35, 50, fifty)
ctx.make full()
ctx.stroke()

Result:

fourth square, oops same style

Someday you lot desire to add a make full/stroke to your shapes, explicitly define the styles.

Optimizing our Code with Classes

Making use of classes we tin can create a robust Rectangle object and make clean upward our code.

Classes are functions that create Objects. We want to create Rectangle objects that contain data about themselves, such as their position, styles, area, and dimensions.

I won't become into much detail on classes as it's not required and you tin can become by with normal functions. Cheque the MDN documentation folio on classes to learn more virtually them.

rectangle course

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 than canvas functions were introduced in the draw method:

ctx.relieve() — saves the electric current styles

ctx.restore() — restores the terminal saved styles

We use these methods to foreclose the issue nosotros saw with the fourth square that had unexpected colors.

Canvas stores styles on a stack structure. When we call ctx.relieve() it pushes the electric current styles onto the stack and calling ctx.restore() pops information technology off the stack.

style stack animated

I only saved ane set of styles in this animation but y'all can save every bit many times as you desire and restore the most recent 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

Nosotros can now first putting this Rectangle class to apply:

create a new square using Rectangle class

The Event:

square drawing from rectangle class

Note: I added a grid for the screenshots. We'll be making a grid at the cease of this department.

We tin can go along reusing the class to make more than squares/rectangles:

child squares nonsense

We create an array and populate it with new Rectangles positioned based on the mySquare object created before. Then we loop over the array and call the draw method on every foursquare.

What practise we become from all that code?

child squares?

Well… it'due south something.

I know this is all boring and tedious simply we've covered the nuts of canvas and y'all've at least seen what a class looks similar now. Let's finish creating more shapes. (it'll become quicker from now on I hope)

Lines 🔗

Rectangles are the only pre-defined shape with sheet, we create other shapes on our own. We can employ lines to build the foundation of these shapes.

using lines to make trapezoid-like shapes

The Consequence:

trapezoid things

New Methods:

ctx.moveTo(x, y) — you lot can think of this as moving our virtual "pen", we utilize it to fix the starting betoken for the showtime line

ctx.lineTo(x, y) — creates a line to X, Y; the starting point is the last position of our "pen". This allows us to start new lines at the endpoint of previous lines.

ctx.closePath() — when using a stroke nosotros need to call this to draw the final line and shut the path. Fill will automatically close the path

Note: If you demand curved lines then you can utilize Bézier curves with the quadratic or cubic bézier curve functions. I'll cover them in another tutorial to keep this one from becoming likewise long.

Text 🔤

If you e'er worked with whatever kind of text editor like to Microsoft Word or any of Adobe's tools, then these options will be familiar to y'all.

draw text on sail example

stroked vs filled text

ctx.strokeText(text, ten, y) — creates the text path and strokes it

ctx.fillText(text, x, y) — same equally in a higher place but fills the text

ctx.font(CSSFontString) — set 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 crave knowledge of font blueprint, which is outside the scope of this tutorial.

  • ctx.textAlign
  • ctx.textBaseline

Circles & Partial Circles (arcs) 🔴

circles / arcs code

resulting circles/arcs

The only new function here is the arc method.

arc(x, y, radius, startAngle, endAngle, antiClockwise)

Ten, Y — defines the position of the center point, non the top left

radius — the size of the circle/arc

startAngle, endAngle — I think 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 one-half a circle, 2Ï€ gives you a full circle.
Watch this video for more on the math of a circle

Triangles 🔺

As there are no triangle functions, we take to make them ourselves using lines.

triangle lawmaking

triangles consequence

Nil new hither. Refer to the sections higher up if yous're lost. (or inquire in the comments)

Quiz: Bones Shapes

  1. What arguments does the rect(_, _, _, _) part take?
  2. After you've used the rect function, what two methods can draw the rectangle to the screen? (the same functions for whatever path)
  3. What function can create circles?
  4. What ii backdrop can we fix to change the make full and outline styles?
  5. How do you set the starting position when using lineTo(x,y)

Answers: (links to related MDN pages)

  1. Rect function docs
  2. Drawing method ane, drawing method 2
  3. Part to draw circles
  4. strokeStyle, fillStyle
  5. ctx.moveTo(x,y)

Challenge: Visualize the Canvas Coordinate Organization

Use what you learned to depict a coordinate plane or filigree with X and Y starting at the tiptop left and end where the sail ends.

Examples

grid from MDN

animated coordinates from before

Tips

  • Use for loops to create multiple lines
  • Information technology can exist a full filigree, just text, or lines with tick marks... Brand the grid you will want to use
  • As we haven't covered animation yet, don't worry about animating it. The example above was animated only for sit-in purposes.

Solution
Don't worry if y'all didn't solve it, this one is challenging.

I started past making a new JS file and loading it instead of the example 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.

initial setup for the grid solution

Now, decide if you desire to make a reusable Grid grade or create something simpler. I will go along it uncomplicated for this example solution by using merely one function.

fractional grid solution

Look at the above code, then endeavour to fill in the blanks yourself if you haven't already solved it. The next snippet will exist the complete code.

example solution consequence
terminal case grid code

Feel free to tweak your grid and save it for future utilize. I saved the animated ane every bit an NPM package to apply with upcoming tutorials.

Final Challenge: Draw Some Art

Now it's time to put everything you've learned to use, hither's your challenge:

Draw a movie using a combination of the shapes we learned.
Find some reference images or make something up.

Ideas

  • Emojis / Faces
  • Flags (Japan'southward flag? 😂)
  • 2D Game/Cartoon Characters
  • Logos
  • Charts (bar chart, pie nautical chart, etc) — a little more than avant-garde and I'll be doing another tutorial on charts but if you desire to try it on your own go for it.
  • Landscape — draw a house, some grass, a sunday or perhaps a starry night sky
  • Search for examples on CodePen to get ideas (prepare to be overwhelmed past the crazy art some people make)

Tips

  • Use canvass.height / 2 and canvas.width / 2 to get the center X, Y of the canvas
  • If you did the grid claiming from earlier, now is a good time to apply it
  • If your drawing needs a lot of curves, await into the bezier curve functions: quadraticCurveTo and bezierCurveTo
  • Effort finding some examples on CodePen
  • Keep it unproblematic. This challenge is just to do drawing shapes on the canvas, not to create some complex game grapheme.

When you finish share a link to your CodePen / GitHub repository in the comments.

Reflection

What did you struggle with the most? Or was everything a cakewalk? What could have been unlike? I would beloved to hear your feedback in the comments. Otherwise, note what y'all struggled with and spend more than time researching and reviewing that topic.

Resource and Links

Dorsum to Alphabetize Page

Thanks for Reading!

I had to cutting a lot of information to go along this tutorial from getting also long but we'll be covering pretty much everything throughout the series.

I would love to hear your feedback and questions! Get out a comment beneath or message me on Twitter.

How To Draw Squares In Convas C# Wpf,

Source: https://codeburst.io/creating-and-drawing-on-an-html5-canvas-using-javascript-93da75f001c1

Posted by: vangentler63.blogspot.com

0 Response to "How To Draw Squares In Convas C# Wpf"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel