Skip to content

Instantly share code, notes, and snippets.

@compupro
Last active April 30, 2019 16:38
Show Gist options
  • Save compupro/19a5dd1723252567470e09c53c4e4869 to your computer and use it in GitHub Desktop.
Save compupro/19a5dd1723252567470e09c53c4e4869 to your computer and use it in GitHub Desktop.
WritingBox.js - Lets you turn a canvas into a canvas you can write on with your mouse
class WritingBox {
/*Define a canvas as a WritingBox by instantiating a WritingBox with the id of the canvas
elemId: The id of the <canvas> element*/
constructor(elemId){
this.writingArea = document.getElementById(elemId);
this.gfxCtx = writingArea.getContext("2d");
this.clickX = [];
this.clickY = [];
this.clickDrag = [];
this.writing;
var self = this;
writingArea.addEventListener("mousedown", function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
self.writing = true;
self.addClick(mouseX, mouseY);
self.redraw();
});
writingArea.addEventListener("mousemove", function(e){
if (self.writing){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
self.addClick(mouseX, mouseY, true);
self.redraw();
}
});
writingArea.addEventListener("mouseup", function(e){
self.writing = false;
});
writingArea.addEventListener("mouseleave", function(e){
self.writing = false;
});
}
addClick(x, y, dragging){
this.clickX.push(x);
this.clickY.push(y);
this.clickDrag.push(dragging);
}
redraw(){
this.gfxCtx.clearRect(0, 0, this.gfxCtx.canvas.width, this.gfxCtx.canvas.height); // Clears the canvas
this.gfxCtx.strokeStyle = "#000000";
this.gfxCtx.lineJoin = "round";
this.gfxCtx.lineWidth = 5;
for(var i=0; i < this.clickX.length; i++) {
this.gfxCtx.beginPath();
if (this.clickDrag[i] && i){
this.gfxCtx.moveTo(this.clickX[i-1], this.clickY[i-1]);
} else {
this.gfxCtx.moveTo(this.clickX[i]-1, this.clickY[i]);
}
this.gfxCtx.lineTo(this.clickX[i], this.clickY[i]);
this.gfxCtx.closePath();
this.gfxCtx.stroke();
}
}
clearWritingArea(){
this.clickX = [];
this.clickY = [];
this.clickDrag = [];
this.redraw();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment