Skip to content

Instantly share code, notes, and snippets.

@zvodd
Created March 24, 2021 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zvodd/d322c0e12cb9838a0b8da5b036a4f061 to your computer and use it in GitHub Desktop.
Save zvodd/d322c0e12cb9838a0b8da5b036a4f061 to your computer and use it in GitHub Desktop.
drawing stuff in canvas
<html>
<head>
<style>
.container{ display:inline-flex;}
#backButton button{width:100%; height:100%}
#nextButton{ }
#nextButton button{width:100%; height:100%}
</style>
</head>
<body>
<center>
<div class=container>
<div id=backButton><button>&lt;</button></div>
<canvas width=600 height=600></canvas>
<div id=nextButton><button>&gt;</button></div>
</div>
<center>
<script>
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext('2d');
ctx.scale(6, 6);
const clear =() => {
ctx.fillStyle ='#FFFFFF'
ctx.fillRect(0,0, 100,100)
}
const grid = (width=0.2,color='#d2e8fb')=>{
for (let i = 0; i < 11; i++){
line([0,i*10], [100,i*10], color=color, width=width)
line([i*10,0 ], [i*10, 100], color=color, width=width)
}
}
const line = ([ax,ay],[bx,by], color='#000000', width=0.2) =>{
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.beginPath()
// render in RightHand coords: Y+ => Up
ctx.moveTo(ax, 100 - ay);
ctx.lineTo(bx, 100 - by);
ctx.stroke();
}
const vAdd = ([ax,ay],[bx,by]) => ([ax+bx, ay+by])
const vSub = ([ax,ay],[bx,by]) => ([ax-bx, ay-by])
const vDot = ([ax,ay],[bx,by]) => (ax*bx + ay*by)
const demo1 = ()=>{
Org = [50,50]
A = [5, 12]
line(Org, vAdd(Org,A), color='red')
}
const demo2 = ()=>{
Org = [50,50]
A = [40, 0]
line(Org, vAdd(Org,A), color='green')
}
const demo3 = ()=>{
Org = [50,50]
A = [5, 12]
B = [40, 0]
C = vSub(A,B)
line(vAdd(Org,B), vAdd(vAdd(Org,B), C), color='blue')
}
const demo4 = ()=>{
l1 =[0,20]
l2 = [100,20]
line(l1,l2)
a1 = [10,80]
a2 = [40,5]
line(a1,a2, color='blue')
}
demo5 = ()=>{
demo4()
l1 =[0,20]
l2 = [100,20]
a1 = [10,80]
a2 = [40,5]
// remember this lines are not the vectors...
b2 = vAdd(a2, vSub(a1,a2))
//vAdd(a2,[-a1[0], a1[1]- a2[1]])
line(a2,b2, color='red')
}
//let DEMOS=[demo4, demo5]
let DEMOS=[demo1, ()=>(demo1() || demo2()), ()=>(demo1() || demo2() || demo3()), ()=>(null)]
let DEMO_POS=0;
const nextDemo = (back=false)=>{
clear()
grid()
const indx = back? 0 :(DEMO_POS++) % (DEMOS.length)
DEMOS[indx]()
}
grid()
let events = [
["#backButton", 'click', (e)=>(e.preventDefault() || nextDemo(true))],
["#nextButton", 'click', (e)=>(e.preventDefault() || nextDemo())]
]
events.map(([s,e,h])=>{
document.querySelector(s).addEventListener(e, h)
})
</script>
<body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment