要回答#1,这是在路径中找到随机点的一种不太好的方法:http: //jsfiddle.net/Aj7Rw/
var points = [[73, 192],
[73, 160],
[340, 23],
[500, 109],
[499, 139],
[342, 93]],
minX,maxX,minY,maxY;
// find min and max values
for (var i = 0; i < points.length; i++){
var point = points[i];
if (minX == undefined || point[0] < minX)
minX = point[0];
if (maxX == undefined || point[0] > maxX)
maxX = point[0];
if (minY == undefined || point[1] < minY)
minY = point[1];
if (maxY == undefined || point[1] > maxY)
maxY = point[1];
}
// draw the path so we can use isPointInPath
var can = document.getElementById("test"),
ctx = can.getContext('2d');
ctx.beginPath();
ctx.moveTo(points[0][0],points[0][1]);
for (var i = 1; i < points.length; i++)
ctx.lineTo(points[i][0],points[i][1]);
ctx.closePath();
ctx.stroke();
// generate some random points.
for (var i = 0; i < 250; i++){
var found = false, iterations = 0;
while(!found){
iterations++;
var x = Math.floor(Math.random()*(maxX-minX)+minX);
var y = Math.floor(Math.random()*(maxY-minY)+minY);
if (ctx.isPointInPath(x,y)){
found = true;
ctx.fillRect(x-3,y-3,6,6);
console.log(x,y, iterations); // I'm logging the number of iterations it took to generate a point within the poly so you can get an idea of the lack of efficiency.
}
}
}