Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to add button in canvas html5

/*You can solve this multiple ways like using html button
 suggested in the comments.

But if you do need to handle click events inside your canvas
 you can do something like this:

Add a click handler to the canvas and when the mouse pointer
 is inside your bounding rectangle you can fire your click function:
*/

//Function to get the mouse position
function getMousePos(canvas, event) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}
//Function to check whether a point is inside a rectangle
function isInside(pos, rect){
    return pos.x > rect.x && pos.x < rect.x+rect.width && pos.y < rect.y+rect.height && pos.y > rect.y
}

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//The rectangle should have x,y,width,height properties
var rect = {
    x:250,
    y:350,
    width:200,
    height:100
};
//Binding the click event on the canvas
canvas.addEventListener('click', function(evt) {
    var mousePos = getMousePos(canvas, evt);

    if (isInside(mousePos,rect)) {
        alert('clicked inside rect');
    }else{
        alert('clicked outside rect');
    }   
}, false);
Comment

PREVIOUS NEXT
Code Example
Javascript :: js alphabets array 
Javascript :: variable key name js 
Javascript :: vue watch handler 
Javascript :: create angular app with routing and scss 
Javascript :: mongoose populate filter 
Javascript :: parse int into 2 digits format javascript 
Javascript :: javascript infinite loop 
Javascript :: code for adding new elements in javascriipt js 
Javascript :: change value of key in array of objects javascript 
Javascript :: for each python json 
Javascript :: powershell json = get value by key 
Javascript :: firebase storage javascript delete document 
Javascript :: delete all node modules 
Javascript :: javascript check if is nan 
Javascript :: javascript date to string format 
Javascript :: js wait 
Javascript :: transform javascript 
Javascript :: dynamically adding marker react native mapbox 
Javascript :: trigger window resize 
Javascript :: react native shaddow 
Javascript :: electron js development auto refresh 
Javascript :: resize image react native 
Javascript :: jquery addeventlistener 
Javascript :: execute javascript when page finished loading 
Javascript :: javascript dynamicly include another js file 
Javascript :: date split in javascript 
Javascript :: generate random hex code 
Javascript :: vue fetch api 
Javascript :: js int to alphabet 
Javascript :: string.find javascript 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =