Skip to content

Instantly share code, notes, and snippets.

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 doc22940/0ee7cfdf1c8eb945ca6e938555fcca4c to your computer and use it in GitHub Desktop.
Save doc22940/0ee7cfdf1c8eb945ca6e938555fcca4c to your computer and use it in GitHub Desktop.
Hitomezashi stitching generator
<canvas id="cnv">click or resize for a new pattern</canvas>
let i = 0;
let j = 0;
let n;
let rid = null;
const ctx = cnv.getContext("2d");
let cw = (cnv.width = window.innerWidth);
let ch = (cnv.height = window.innerHeight);
let size = Math.max(cw,ch);
let d = 25;
let v = [];
let h = [];
class Line {
constructor(x1, y1,type) {
this.x1 = x1;
this.y1 = y1;
this.length = 0;
this.type = type;
this.lineDashOffset = Math.random() > 0.5 ? d : 0;
this.getCoords();
}
getCoords(){
if(this.type == "v"){
this.x2 = this.x1;
this.y2 = this.y1+this.length;
}else{
this.x2 = this.x1+this.length;
this.y2 = this.y1;
}
}
draw() {
ctx.strokeStyle = "hotpink";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(this.x1, this.y1);
ctx.lineTo(this.x2, this.y2);
ctx.setLineDash([d, d]);
ctx.lineDashOffset = this.lineDashOffset;
ctx.stroke();
}
update(){
if(this.length < size){this.length++}
}
}
function pattern() {
v=[];
h=[];
i = 0;
j = 0;
for (let x = 0; x < size; x += d) {
v.push(new Line(x, 0, "v"));
}
n = v.length;
for (let y = 0; y < size; y += d) {
h.push(new Line(0, y, "h"));
}
}
pattern();
function Draw(){
rid = requestAnimationFrame(Draw);
ctx.clearRect(0,0,cw,ch)
if(v[i].length < size){
v[i].length+=d;h[i].length+=d;
v[i].getCoords();h[i].getCoords();
}else{i++}
v.map(l=>{l.draw()})
h.map(l=>{l.draw()})
if(i >= n-1){cancelAnimationFrame(rid); rid=null;}
}
Draw();
cnv.addEventListener("click", ()=>{pattern();Draw()});
function Init() {
cw = cnv.width = window.innerWidth;
ch = cnv.height = window.innerHeight;
size = Math.max(cw,ch);
if(rid){cancelAnimationFrame(rid); rid=null;}
pattern();
Draw()
}
window.setTimeout(function () {
Init();
window.addEventListener("resize", Init, false);
}, 15);
canvas{background:black;}
body{overflow:hidden;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment