beginPath()
starts a new shape
stroke()
draws the lines.
strokeStyle
fill()
draws the shape filled (if it can).
fillStyle
let canvas = document.getElementById("shapes"); let ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; ctx.strokeStyle = "green"; ctx.lineWidth = 2; let offset = 0; function Shape(off, ctx){ ctx.moveTo(off+10,off+10); ctx.lineTo(off+40, off+10); ctx.lineTo(off+40, off+40); ctx.lineTo(off+10, off+10); } ctx.beginPath() Shape(offset, ctx); ctx.fill(); offset += 75; ctx.beginPath() Shape(offset, ctx); ctx.stroke(); offset += 75; ctx.beginPath() Shape(offset, ctx); ctx.fill(); ctx.stroke();
Position
end -start
is the length of the line.
start + (end-start)*p
is the point p% along that line in that dimension.
<canvas id="line" height="100" width="500" style="border:2px solid #000000;"></canvas> Position <input type="range", min='0' max='100' value ='50' id="position" onchange = "Update()"> <script> let canvas1 = document.getElementById("line"); let w1 = canvas1.width; let h1 = canvas1.height; let ctx1 = canvas1.getContext("2d"); let pos = 0; let xend = w1-10; let xstart = 10; let slider = document.getElementById("position"); slider.value = pos; Update(); function Update() { pos = parseInt(slider.value )/100; ctx1.fillStyle="green"; ctx1.fillRect(0,0,w1,h1); ctx1.strokeColor = "black"; ctx1.beginPath(); ctx1.moveTo(xstart,h1/2); ctx1.lineTo(xend,h1/2); ctx1.stroke(); ctx1.fillStyle="red"; let x = xstart + ( xend-xstart)*pos; ctx1.fillRect(x-3, h1/2-3,6,6); } </script>
<canvas id="dragon" height="200" width="200" style="border:2px solid #000000;"></canvas> <script> let canvas2 = document.getElementById("dragon"); let w2 = canvas2.width; let h2 = canvas2.height; let ctx2 = canvas2.getContext("2d"); ctx2.strokeStyle = "black"; let x1 = w2 * 0.3; let y1 = h2 * 0.3; let x2 = w2 * 0.8; let y2 = h2 * 0.8; ctx2.beginPath(); ctx2.moveTo(x1,y1); ctx2.lineTo(x2,y2); ctx2.stroke(); // find the change in each dimension. let dx = x2-x1; let dy = y2-y1; // find the midpoint of the line let mx = x1 + (dx)*.5; let my = y1 + (dy)*.5; ctx2.fillStyle = "red"; ctx2.fillRect(mx-2, my-2, 4,4); // find the point 1/2 dx,dy away going one direction let e1x = mx + dy/2; let e1y = my - dx/2; ctx2.beginPath(); ctx2.strokeStyle ="green"; ctx2.moveTo(mx,my); ctx2.lineTo(e1x, e1y); ctx2.stroke(); // find the point 1/2 dx,dy away going the other direction let e2x = mx - dy/2; let e2y = my + dx/2; ctx2.beginPath(); ctx2.strokeStyle ="blue"; ctx2.moveTo(mx,my); ctx2.lineTo(e2x, e2y); ctx2.stroke(); </script>