Prev Demo
HTML5
>
Canvas Hover
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Canvas Hover</title> </head> <body> <h4>Hover the rectangle to change the color</h4> <canvas id="mycanvas" width=300 height=200 style="border:5px solid green"></canvas> <script> var canvas = document.getElementById("mycanvas"), context = canvas.getContext("2d"), rects = [ { x: 20, y: 10, w: 50, h: 50 }, { x: 200, y: 10, w: 50, h: 50 } ], i = 0, r; while (r = rects[i++]) context.rect(r.x, r.y, r.w, r.h); context.fillStyle = "blue"; context.fill(); canvas.onmousemove = function (e) { var rect = this.getBoundingClientRect(), x = e.clientX - rect.left, y = e.clientY - rect.top, i = 0, r; context.clearRect(0, 0, canvas.width, canvas.height); while (r = rects[i++]) { context.beginPath(); context.rect(r.x, r.y, r.w, r.h); context.fillStyle = context.isPointInPath(x, y) ? "blue":"yellow"; context.fill(); } }; </script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output