我有一些词。所有词都在某个“对象”之王中。这个词可以在画布上移动,我需要得到所有交叉点的数组,就像在这个例子中一样,但不需要将文本转换为 SVG。paperjs.org/examples/path-intersections 谢谢。
问问题
650 次
1 回答
6
您可以通过比较两个词的 imageData 来检测两个词之间的所有交点。
无论单词与哪个像素相交,两个单词的 alpha 值都将大于零。
这是代码和小提琴:http: //jsfiddle.net/m1erickson/ecAvt/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px; }
#wrapper{
position:relative;
width:400px;
height:400px;
}
#canvasTop,#canvasBottom,#canvasDots{
position:absolute; top:0px; left:0px;
border:1px solid green;
width:100%;
height:100%;
}
#canvasTop{
border:1px solid red;
}
#canvasDots{
border:1px solid blue;
}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvasTop");
var ctx=canvas.getContext("2d");
ctx.font="192px verdana";
ctx.strokeText("No",40,220);
var canvas2=document.getElementById("canvasBottom");
var ctx2=canvas2.getContext("2d");
ctx2.font="192px verdana";
ctx2.strokeStyle="lightgray";
ctx2.strokeText("Yes",40,300);
var canvas3=document.getElementById("canvasDots");
var ctx3=canvas3.getContext("2d");
ctx3.fillStyle="blue";
var canvasOffset=$("#canvasTop").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var imageData2=ctx2.getImageData(0,0,canvas2.width,canvas2.height);
var data2=imageData2.data;
var dotsVisible=false;
function showIntersections(){
var imageData=ctx.getImageData(0,0,canvas.width,canvas.height);
var data=imageData.data;
ctx3.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<data.length;i+=4){
if(data[i+3]>120 && data2[i+3]>120){
var y=parseInt(i/canvas.width/4);
var x=i/4-y*canvas.width;
ctx3.beginPath();
ctx3.arc(x,y,3,0,Math.PI*2);
ctx3.closePath();
ctx3.fill();
}
}
dotsVisible=true;
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
showIntersections();
}
function handleMouseUp(e){
isDown=false;
}
function handleMouseOut(e){
isDown=false;
}
function handleMouseMove(e){
if(dotsVisible){ctx3.clearRect(0,0,canvas.width,canvas.height);}
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeText("No",mouseX,mouseY+100);
}
$("#canvasDots").mousedown(function(e){handleMouseDown(e);});
$("#canvasDots").mousemove(function(e){handleMouseMove(e);});
$("#canvasDots").mouseup(function(e){handleMouseUp(e);});
$("#canvasDots").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h3>Move "NO" with mouse</h3>
<h3>Click to find intersections</h3>
<div id="wrapper">
<canvas id="canvasBottom" width=400 height=400></canvas>
<canvas id="canvasTop" width=400 height=400></canvas>
<canvas id="canvasDots" width=400 height=400></canvas>
</div>
</body>
</html>
于 2013-11-13T16:43:15.920 回答