Adding a place to draw.
Notes
- We will use the HTML canvas to draw.
- This requires a closing
</canvastag, don't forget it. - I like to add
- id = "someid"
- height="400"
- width=400
- style="border: 1px solid black;"
- You can do this with a css if you like.
- Edit your
newton.htmlfile and add<body> <canvas id="MyCanvas" height="400" width="400" style="border: 2px solid black;"> </canvas> <div id="output">
- This requires a closing
- Next grab some useful information about the canvas
- These are global variables, so we don't have to constantly grab the information.
-
// // grab some canvas information const canvas = document.getElementById("MyCanvas") const height = canvas.height const width = canvas.width ... outputArea.innerHTML = "The canvas is "; outputArea.innerHTML += "<br> width: "+ width; outputArea.innerHTML += "<br> height: "+ height; - note comments in javascript are the same as c++ // and /* */
- The context
- Canvases can be used in different ways.
- The context determines that.
- Use canvas.getContext("2d") for now.
- We will look at other contexts later.
-
// get the canvas and associated parts const canvas = document.getElementById("MyCanvas") const ctx = canvas.getContext("2d") const height = canvas.height - We will use this everywhere.
- Just for fun let's draw an x.
- We will do this using context methods.
- It starts with
ctx.beginPath() - Move to a starting point
ctx.moveTo(0,0) - Line to an ending point
ctx.lineTo(width, heigth) - Finish with
ctx.stroke() -
const width = canvas.width ctx.beginPath() ctx.moveTo(0,0) ctx.lineTo(width,height) ctx.stroke()
- It starts with
- if you wish add
ctx.strokeStyle="Red"between begin and stroke. - Add the command to draw the other side of the x.
- We will do this using context methods.