vs6262
Silver Member | Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
Код: <!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; } #canvas{border:1px solid red;} </style> <script> $(function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var $canvas=$("#canvas"); var canvasOffset=$canvas.offset(); var offsetX=canvasOffset.left; var offsetY=canvasOffset.top; var scrollX=$canvas.scrollLeft(); var scrollY=$canvas.scrollTop(); var $results=$("#results"); // create an object holding all polygon points var triangle=[{x:100,y:50},{x:150,y:100},{x:50,y:100}]; var poly=[{x:100,y:250},{x:150,y:300},{x:50,y:300},{x:70,y:230}]; // draw the polygon define(triangle); ctx.fill(); define(poly); ctx.fill(); // define the polygon function define(polygon){ ctx.beginPath(); ctx.moveTo(polygon[0].x,polygon[0].y); for(var i=1;i<polygon.length;i++){ ctx.lineTo(polygon[i].x,polygon[i].y); } ctx.closePath(); } function hitTest(polygon){ // redefine the polygon // (necessary to isPointInPath to work define(polygon); // ask isPointInPath to hit test the mouse position // against the current path return(ctx.isPointInPath(mouseX,mouseY)); } function handleMouseMove(e){ e.preventDefault(); mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); // check if the mouse is inside the polygon var isInside=hitTest(poly); if(isInside){ //$results.text("Mouse is inside the Triangle"); ctx.fillStyle="#FF0000"; ctx.fill(); }else{ //$results.text("Outside"); } var isInside=hitTest(triangle); if(isInside){ //$results.text("Mouse is inside the Triangle"); ctx.fillStyle="#0000FF"; ctx.fill(); }else{ //$results.text("Outside"); } } $("#canvas").click(function(e){handleMouseMove(e);}); }); // end $(function(){}); </script> </head> <body> <p id="results">Hit results</p> <canvas id="canvas" width=300 height=500></canvas> </body> </html> |
| Всего записей: 2188 | Зарегистр. 25-02-2013 | Отправлено: 12:19 05-04-2017 | Исправлено: vs6262, 16:53 05-04-2017 |
|