Skip to content

Instantly share code, notes, and snippets.

View Garrett-Bodley's full-sized avatar
🐙
Attending Recurse Center

Garrett Bodley Garrett-Bodley

🐙
Attending Recurse Center
View GitHub Profile
@Garrett-Bodley
Garrett-Bodley / OldResize.js
Last active February 23, 2021 18:30
Old Resize and Undo Code
// this.width and this.height are just shorthands for this.canvas.width and this.canvas.height
undoLast = () => {
this.stateLog.pop();
this.clearCanvas();
if(this.stateLog.length > 0){
const imageData = this.stateLog[this.stateLog.length - 1]
// This is the part that's needed to be fixed
@Garrett-Bodley
Garrett-Bodley / DynamicallyResize.js
Last active February 23, 2021 18:31
Dynamically Resize the Canvas Element
undoLast = () => {
this.stateLog.pop();
this.clearCanvas();
if(this.stateLog.length > 1){
const imageData = this.stateLog[this.stateLog.length - 1]
// This is the part that's different
this.ctx.putImageData(imageData, (this.width - imageData.width)/2, (this.height - imageData.height)/2)
@Garrett-Bodley
Garrett-Bodley / UndoLast.js
Last active February 23, 2021 05:53
Undo Last and Clear Canvas
undoLast = () => {
this.stateLog.pop();
this.clearCanvas();
if(this.stateLog.length > 1){
const imageData = this.stateLog[this.stateLog.length - 1]
this.ctx.putImageData(imageData, (this.width - imageData.width)/2, (this.height - imageData.height)/2)
}
@Garrett-Bodley
Garrett-Bodley / SaveState.js
Created February 23, 2021 05:46
Save canvas state
saveState = () => {
const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
this.stateLog.push(imageData)
}
@Garrett-Bodley
Garrett-Bodley / DrawingFunctions.js
Last active February 23, 2021 18:19
Drawing Functions
startDrawing = (e) => {
this.drawing = true;
this.ctx.beginPath();
this.draw(e);
}
stopDrawing = () => {
if (this.drawing === true){
this.drawing = false;
this.saveState()
@Garrett-Bodley
Garrett-Bodley / AddListeners.js
Last active February 23, 2021 18:19
Add Event Listeners
addListeners(){
this.canvas.addEventListener('mousedown', this.startDrawing)
this.canvas.addEventListener('mouseup', this.stopDrawing)
this.canvas.addEventListener('mouseleave', this.stopDrawing)
this.canvas.addEventListener('mousemove', this.draw)
}
@Garrett-Bodley
Garrett-Bodley / CanvasContext.js
Created February 23, 2021 05:42
Canvas Context
class Sketchpad{
constructor(){
this.canvas = this.createCanvas()
this.ctx = this.canvas.getContext("2d");
}
}
@Garrett-Bodley
Garrett-Bodley / SketchpadConstructor.js
Created February 23, 2021 05:37
Sketchpad constructor
class Sketchpad {
constructor(element){
this.parent = element;
this.canvas = this.createCanvas()
}
createCanvas = () => {
let canvas = document.createElement('canvas');
canvas.id = "canvas"