在悬停时更新 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.
问题是在我绘制了矩形之后,我不确定如何再次选择它来进行调整.
The problem is after I've drawn the rectangle I'm not sure how I select it again to make the adjustment.
我想做什么:
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.
- 将您想要的所有矩形存储为简单对象
- 每次鼠标在画布元素上移动:
- 获取鼠标位置
- 遍历对象列表
- 使用 isPointInPath() 检测悬停"
- 重绘两个状态
示例
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屋!
查看全文