Skip to content

Instantly share code, notes, and snippets.

@jtenner
Last active December 28, 2021 17:13
Show Gist options
  • Save jtenner/7533570 to your computer and use it in GitHub Desktop.
Save jtenner/7533570 to your computer and use it in GitHub Desktop.
Canvas Button
var priorEvt;
function getMousePos(evt) {
priorEvt = evt = evt || priorEvt;
var rect = canvas.getBoundingClientRect();
if (evt)
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
return {
x: 0,
y: 0
};
}
function CanvasButton(img, x, y, width, height) {
//this function takes an "event" object passed by the canvas click events
function onButton(pos) {
//it determines if the position is greater than x, less than the width
//and greater than y, less than the height
return (x <= pos.x && pos.x <= x + width) &&
(y <= pos.y && pos.y <= y + height);
}
//go ahead and replace this section with whatever you need to draw the image
if (Object.prototype.toString.call(img) === '[object String]')
img = document.getElementById(img);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, x, y, width, height);
//draw region end
//the button isn't toggled by default
var down = false;
canvas.addEventListener("mousedown", function (evt) { //event listener
down = onButton(getMousePos(evt));
});
//handle the document mouseup to reset the "down" variable every time.
document.addEventListener("mouseup", function (evt) {
if (onButton(getMousePos(evt)) && down) {
//we got a click!
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment