更新悬停时的HTML5画布矩形? [英] Update HTML5 canvas rectangle on hover?
本文介绍了更新悬停时的HTML5画布矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码在画布上绘制一个矩形,但是当我将鼠标悬停在其上时,我希望该矩形改变颜色。
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.
问题
我想要做什么:
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();
});
推荐答案
框与画布。 Canvas是一个位图,所以悬停逻辑必须手动实现。
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.
- 将所有矩形存储为简单对象
- 对于每个鼠标在canvas元素上移动:
- 使用isPointInPath()检测悬停
<
- 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 - 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/>
这篇关于更新悬停时的HTML5画布矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文