1

所以我对在当代浏览器中引入 Canvas Paths 作为标准对象感到非常兴奋,并且一直试图看看我能从这个新功能中获得多少里程。但是,我对这些对象如何与 isPointInPath() 方法(可能还有其他基于路径的方法)交互的理解显然有些缺陷。

正如下面前两个测试函数所演示的,我可以得到要被 isPointInPath() 方法识别的绘制路径。但是,当我将路径定义为对象时,该方法将停止工作(即使路径对象可以被识别用于其他目的,例如填充)。

function startGame(){ //Initiating Environment Variables
	gamemap = document.getElementById("GameMap")
	ctx = gamemap.getContext("2d")
	testCircleBounds()
	testVarCircleBounds()
	testObjCircleBounds()
	testMultiObjCircleBounds()
}

function testCircleBounds() { //Minimalist Test of Path Methods
	ctx.beginPath()
	ctx.arc(250,250,25,0,2*Math.PI)
	console.log(ctx.isPointInPath(250,250)) //point in path detected
	ctx.closePath()
	console.log(ctx.isPointInPath(250,250)) //point in path still detected
	ctx.stroke()
	ctx.fillStyle = "yellow"
	ctx.fill() //fills great
}

function testVarCircleBounds() { //Test of Path Methods with Variables
	x_cen = 250; y_cen = 250; rad = 15
	ctx.beginPath()
	ctx.arc(x_cen,y_cen,rad,0,2*Math.PI)
	ctx.closePath()
	console.log(ctx.isPointInPath(x_cen,y_cen)) //true yet again
	ctx.stroke()
	ctx.fillStyle = "orange"
	ctx.fill() //also fills great
}

function testObjCircleBounds() { //Test of Path Methods with Single Stored Path Object
	x_cen = 250; y_cen = 250; rad = 10
	ctx.beginPath()
	lonely_node = new Path2D()
	lonely_node.arc(x_cen,y_cen,10,0,2*Math.PI)
	ctx.closePath()
	console.log(ctx.isPointInPath(x_cen,y_cen)) //point in path not found!
	ctx.stroke(lonely_node)
	ctx.fillStyle = "red"
	ctx.fill(lonely_node) //but ctx.fill notices the path just fine
}


function testMultiObjCircleBounds(){ //Test of Paths Methods with Multi-Object Referencing
	nodes = [] //initializes set of nodes as array
	for (i=0; i<25; i++) { //generates 25 nodes
		nodes[i] = new Path2D() //defines each node as Path object in the array
		node = nodes[i]
		//Places Nodes along the 'horizon' of the map
		x_cen = 20*i + 10
		y_cen = 100
		ctx.beginPath(node) //"node" argument probably not helping?
		node.arc(x_cen,y_cen,8,0,2*Math.PI)
		console.log(ctx.isPointInPath(x_cen,y_cen)) //still returns false!
		ctx.closePath(node)
		ctx.stroke(node)
		console.log(ctx.isPointInPath(x_cen,y_cen)) //arrgh!!
	}
	// Fill can also be selectively applied to referenced path objects
	for (i=0; i<25; i=i+2) {
		ctx.fill(nodes[i])
	}
		
}
<!DOCTYPE html>
<html>
<head>
<title>Wrap Around Beta</title>
<script src="Circuity_PathObjectTest.js"></script>
</head>

<body onload='startGame()'>
	
<canvas id="GameMap" width="500" height="500" style="border:1px solid #000000"></canvas>

</body>

</html>

这从根本上来说是思考 Path2D 对象和在画布上记录“命中”区域的错误方式吗?如果是这样,是否有另一种技术(为绘制的每条路径或沿该脉络的东西保存画布上下文)会产生所需的效果?

4

1 回答 1

2

您必须将正在测试的 Path2D 的引用发送到 isPointInPath:

ctx.isPointInPath( lonely_node, x_cen, y_cen ) 
于 2016-07-05T21:42:08.210 回答