user11406 user11406 - 9 months ago 93
HTML Question

Update HTML5 canvas rectangle on hover?

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");

this.fillStyle = 'red';


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


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 -,
      i = 0, r;
  ctx.clearRect(0, 0, canvas.width, canvas.height); // for demo
  while(r = rects[i++]) {
    // add a single rect to path:
    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";