Skip to content

Instantly share code, notes, and snippets.

@Luftare
Created October 29, 2017 08:12
Show Gist options
  • Save Luftare/19574e192dbe8ee5d7db8272093fd0bd to your computer and use it in GitHub Desktop.
Save Luftare/19574e192dbe8ee5d7db8272093fd0bd to your computer and use it in GitHub Desktop.
html canvas fx component
const fx = {
flashCounter: 0,
flashDamp: 10,//increase to make flash faster, decrease for longer flash
flashColor: "#fff",
shakeCounter: 0,
shakeAmplitude: 20,
shakeDamp: 5,//increse to make shake shorter, decrease to shake longer
shakeSpeed: 0.1,
shake(amount = 1) {
this.shakeCounter = amount;
},
flash(color = "#fff") {
this.flashColor = color;
this.flashCounter = 1;
},
update(dt) {//dt in seconds, call this method on every loop cycle
this.flashCounter = Math.max(0, this.flashCounter - dt * this.flashDamp);
this.shakeCounter = Math.max(0, this.shakeCounter - dt * this.shakeDamp);
},
preDraw(ctx) {//call this methods right after clearing everything and before drawing anything
ctx.translate(
Math.cos(Date.now() * this.shakeSpeed) * this.shakeCounter * this.shakeAmplitude,
Math.sin(Date.now() * this.shakeSpeed) * this.shakeCounter * this.shakeAmplitude,
)
},
draw(ctx) {//call this after drawing everything else
ctx.fillStyle = this.flashColor;
ctx.globalAlpha = this.flashCounter;
ctx.fillRect(0, 0, innerWidth, innerHeight);
ctx.globalAlpha = 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment