使用Paper.js将鼠标光标悬停在特定画布路径上时更改鼠标光标

时间:2013-04-09 00:23:56

标签: html5-canvas paperjs

实际上(使用w3.org doc的示例http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas/#dom-context-2d-ispointinpath)我确实知道如何在原始HTML5Canvas / JavaScript中完成它:http://jsfiddle.net/QTu9E/4/

上面我使用了isPointInPath(x, y)语法,但根据提到的文档,还有isPointInPath(path, x, y[, w ]),其中可以给出一定的路径来检查。

这个可能是问题解决者,但我无法将paperjs的Path对象传递给它!

我会继续寻找解决方案,因为和其他任何人一样,我有最后期限,但任何帮助都会受到赞赏!

2 个答案:

答案 0 :(得分:2)

好的,这是答案!

http://jsfiddle.net/fqaJM/

<canvas id="myCanvas" width="256" height="128"></canvas>
<div id="xycoordinates"></div>

#myCanvas {
    border: 1px solid #c3c3c3;
}
#xycoordinates {
    font: 9pt sans-serif;
}

var canvas = document.getElementById("myCanvas"); // Get canvas

// Some initialisation stuff to make things work out of PaperScript context
// Have to have things to be done this way because jsfiddle don't allow to save source with script type="text/paperscript"
paper.install(window); 
paper.setup(canvas);   

var myPath = new paper.Path.Circle([64, 64], 32); // Red one, with 'pointer' cursor on it
myPath.style = {
    fillColor: '#FF0000'
};
var scndPath = new paper.Path.Circle([192, 64], 32); // Green one, without cursor accent
scndPath.style = {
    fillColor: '#00FF00'
};
paper.view.draw(); // Have to call manually when working from JavaScript directly

var hitOptions = { // Trigger hit only on 'fill' part of the path with 0 tolerance
    segments: false,
    stroke: false,
    fill: true,
    tolerance: 0
};

var tool = new paper.Tool(); // Again manually. Life is much easier with script type="text/paperscript"
tool.onMouseMove = function (event) { // Installig paperjs event 
    var x = event.point.x;
    var y = event.point.y;

    document.getElementById("xycoordinates").innerHTML = "Coordinates: (" + x + "," + y + ")";

    var hitResult = myPath.hitTest(event.point, hitOptions); // isPointInPath

    if (hitResult) {
        document.body.style.cursor = "pointer";
    } else {
        document.body.style.cursor = "default";
    }
};

关键是我错过了paperjs有自己的onMouseMovehitTest(),这是isPointInPath()包装。

不知道是怎么回事,因为我已经在项目中使用它了! Perhabs需要休息一下%)

无论如何,仍然存在一些问题:看起来hitTest()会引发一些奇怪的误报,而且它不会触发它应该发生的地方。用(46,96)和(77,64)坐标检查点!

UPD:刚刚在一个HTML文件中测试了相同的代码,以获得相同的工件:http://pastebin.com/HiYgKnw0

答案 1 :(得分:0)

尝试onMouseEnteronMouseLeave事件,并更改paperjs容器html dom元素的css样式。

http://paperjs.org/reference/item/#onmouseenter

yourPath.onMouseEnter = function (event) {
    paperCanvasContainerDiv.style.cursor = "pointer";
}
yourPath.onMouseLeave = function (event) {
    paperCanvasContainerDiv.style.cursor = "default";
}