我有一个画布,我想更改用户光标(如样式光标指针十字线移动等).是否可以在我的画布的某个区域上更改用户光标而不在这些命中框上引入带有光标样式的"命中框"?
mar*_*rkE 20
在画布上绘制的形状不会单独接收鼠标事件,因此单个形状无法接收悬停事件.
在画布上绘制的形状可以表示为一组路径命令
A Shape == A set of path commands.
// Example: A set of path commands drawing a triangle
context.beginPath();
context.moveTo(50,50);
context.lineTo(75,100);
context.lineTo(25,100);
context.closePath();
Run Code Online (Sandbox Code Playgroud)
要在将光标悬停在各个形状上时更改光标,必须对每个形状(相对于每个路径)进行鼠标命中测试.
您可以使用该isPointInPath方法对形状(路径)进行测试.
要使用isPointInPath你必须重新发出一个形状的路径命令(但不需要描边或填充),然后isPointInPath使用当前鼠标坐标调用:
// first re-issue the path commands for the shape being tested
// and then test if the mouse is inside the shape using isPointInPath
if( context.isPointInPath(mouseX,mouseY) ){
alert('The mouse is inside this shape');
}
Run Code Online (Sandbox Code Playgroud)
这是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
var cursors=['default','w-resize','n-resize'];
var currentCursor=0;
var shapes=[];
shapes.push({
points:[{x:20,y:50},{x:100,y:10},{x:180,y:50},{x:100,y:90}],
cursor:1,
});
shapes.push({
points:[{x:200,y:50},{x:250,y:150},{x:200,y:250},{x:150,y:150}],
cursor:2,
});
for(var i=0;i<shapes.length;i++){
var s=shapes[i];
definePath(s.points);
ctx.stroke();
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
function definePath(p){
ctx.beginPath();
ctx.moveTo(p[0].x,p[0].y);
for(var i=1;i<p.length;i++){
ctx.lineTo(p[i].x,p[i].y);
}
ctx.closePath();
}
function handleMouseMove(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var newCursor;
for(var i=0;i<shapes.length;i++){
var s=shapes[i];
definePath(s.points);
if(ctx.isPointInPath(mouseX,mouseY)){
newCursor=s.cursor;
break;
}
}
if(!newCursor){
if(currentCursor>0){
currentCursor=0;
canvas.style.cursor=cursors[currentCursor];
}
}else if(!newCursor==currentCursor){
currentCursor=newCursor;
canvas.style.cursor=cursors[currentCursor];
}
}Run Code Online (Sandbox Code Playgroud)
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Move the mouse over the shapes and the cursor will change.</h4>
<canvas id="canvas" width=300 height=300></canvas>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11458 次 |
| 最近记录: |