Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  101] [ 4]  / answers: 1 / hits: 66943  / 9 Years ago, fri, march 27, 2015, 12:00:00

I've got some code which draws a rectangle on a canvas, but I want that rectangle to change color when I hover the mouse over it.



The problem is after I've drawn the rectangle I'm not sure how I select it again to make the adjustment.



What I want to do:



var c=document.getElementById(myCanvas);
var ctx=c.getContext(2d);
ctx.rect(20,20,150,100);
ctx.stroke();

$('c.[rectangle]').hover(function(this){
this.fillStyle = 'red';
this.fill();
});

More From » html

 Answers
44

You can't do this out-of-the-box with canvas. Canvas is just a bitmap, so the hover logic has to be implemented manually.



Here is how:




  • Store all the rectangles you want as simple object

  • For each mouse move on the canvas element:

    • Get mouse position

    • Iterate through the list of objects

    • use isPointInPath() to detect a hover

    • Redraw both states




Example





var canvas = document.querySelector(canvas),
ctx = canvas.getContext(2d),
rects = [
{x: 10, y: 10, w: 200, h: 50},
{x: 50, y: 70, w: 150, h: 30} // etc.
], i = 0, r;

// render initial rects.
while(r = rects[i++]) ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = blue; ctx.fill();

canvas.onmousemove = function(e) {

// important: correct mouse position:
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0, r;

ctx.clearRect(0, 0, canvas.width, canvas.height); // for demo

while(r = rects[i++]) {
// add a single rect to path:
ctx.beginPath();
ctx.rect(r.x, r.y, r.w, r.h);

// check if we hover it, fill red, if not fill it blue
ctx.fillStyle = ctx.isPointInPath(x, y) ? red : blue;
ctx.fill();
}

};

<canvas/>




[#67289] Wednesday, March 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;