Created
January 13, 2023 10:43
-
-
Save adierebel/d5385714220499187e368b6d3cf140f9 to your computer and use it in GitHub Desktop.
Erasable HTML Canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<style> | |
body { | |
overflow: hidden; | |
} | |
</style> | |
<img id="scream" src="pic_the_scream.jpg" style="display:none;"> | |
<canvas id="myCanvas" width="540" height="597" style="border:1px solid #d3d3d3;background:cyan;"></canvas> | |
<script> | |
/* Midpoint circle algorithm | |
https://play.google.com/store/apps/details?id=com.google.android.webview | |
function distance(p1, p2) { | |
dx = p2.x - p1.x; dx *= dx; | |
dy = p2.y - p1.y; dy *= dy; | |
return Math.sqrt( dx + dy ); | |
} | |
function clearPixel(ctx, x, y) { | |
ctx.clearRect(x, y, 1, 1); | |
} | |
function clearCirle(ctx, x, y, r) { | |
for (let j=x-r; j<=x+r; j++) { | |
for (let k=y-r; k<=y+r; k++) { | |
if (distance({x:j,y:k}, {x:x,y:y}) <= r) { | |
clearPixel(ctx, j, k); | |
} | |
} | |
} | |
} | |
*/ | |
function clearCircle(ctx, x, y, r) { | |
ctx.beginPath(); | |
ctx.globalCompositeOperation = 'destination-out' | |
ctx.arc(x, y, r, 0, 2 * Math.PI, false); | |
ctx.fill(); | |
ctx.closePath(); | |
} | |
window.onload = function() { | |
let img = document.getElementById("scream"); | |
let canvas = document.getElementById("myCanvas"); | |
let ctx = canvas.getContext("2d"); | |
let isDown = false; | |
let eraseSize = 20; | |
// Draw image | |
ctx.drawImage(img, 10, 10, 520, 577); | |
// Listen touch events | |
canvas.addEventListener('touchmove', (e) => { | |
if (e.touches.length > 0) { | |
let touch = e.touches[0]; | |
let x = touch.pageX - canvas.offsetLeft; | |
let y = touch.pageY - canvas.offsetTop; | |
clearCircle(ctx, x, y, eraseSize); | |
} | |
}); | |
// Listen mouse events | |
document.addEventListener('mouseup', () => { | |
isDown = false; | |
}); | |
canvas.addEventListener('mousedown', () => { | |
isDown = true; | |
}); | |
canvas.addEventListener('mousemove', (e) => { | |
let x = e.pageX - canvas.offsetLeft; | |
let y = e.pageY - canvas.offsetTop; | |
if (isDown) { | |
clearCircle(ctx, x, y, eraseSize); | |
} | |
}); | |
canvas.addEventListener('click', (e) => { | |
clearCircle(ctx, e.pageX-canvas.offsetLeft, e.pageY-canvas.offsetTop, eraseSize); | |
}); | |
}; | |
</script> | |
</body> | |
</html> |
Author
adierebel
commented
Jan 13, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment