线圆相交测试

by Tim Wu

HTML

<script src="https://code.createjs.com/easeljs-0.7.1.min.js"></script>
<script src="https://wuzhiwei.net/libs/gsap/TweenMax.min.js"></script>
<link rel="stylesheet" href="https://wuzhiwei.net/libs/bootstrap/css/bootstrap.min.css">
<script src="https://wuzhiwei.net/libs/ds/cl.js"></script>
<div class="container">
  <div class="panel panel-default">
    <div class="panel-heading">线圆相交测试</div>
    <div class="panel-body">
      <canvas id="stage" class="center-block" width="400" height="220" style="border:1px black solid "></canvas>
    </div>
    <div class="panel-footer">
      <div id="author">Author: <a href="http://wuzhiwei.net/about/" target="_blank">Tim Wu</a>

      </div>
    </div>
  </div>
</div>

CSS

.panel {
  min-width: 450px;
}

.panel-heading {
  text-align: center;
}

#author {
  text-align: right;
}

.center-block {
  text-align: center;
}

#stage {
  margin-bottom: 12px;
}

#start {
  margin-left: 30px;
  margin-right: 30px;
}

JavaScript

var stage = new createjs.Stage('stage');
TweenLite.ticker.addEventListener("tick", stage.update, stage);

var circle = new createjs.Shape();
circle.graphics.beginFill("#FF0000").drawCircle(0, 0, 50);
circle.x = 200;
circle.y = 100;
stage.addChild(circle);

var cc = new createjs.Shape();
cc.graphics.beginFill("#ffffff").drawCircle(0, 0, 1);
cc.x = 200;
cc.y = 100;
stage.addChild(cc);

var p0 = new createjs.Shape();
p0.graphics.beginFill("#000000").drawCircle(0, 0, 5);
p0.x = 50;
p0.y = 130;
stage.addChild(p0);

var p1 = new createjs.Shape();
p1.graphics.beginFill("#000000").drawCircle(0, 0, 5);
p1.x = 350;
p1.y = 130;
stage.addChild(p1);

var w = {
  p0: p0,
  p1: p1
};
w = updateVector(w, true);

var line = new createjs.Shape();
stage.addChild(line);

var il = new createjs.Shape();
stage.addChild(il);

var bl = new createjs.Shape();
stage.addChild(bl);

function drawLine(line, color, p0, p1) {
  line.graphics.clear();
  line.graphics.setStrokeStyle(1);
  line.graphics.beginStroke(color);
  line.graphics.moveTo(p0.x, p0.y);
  line.graphics.lineTo(p1.x, p1.y);
  line.graphics.endStroke();
}

var cv = {
  r: 50,
  p0: {
    x: 200,
    y: 100
  },
  p1: {
    x: 200,
    y: 100
  }
};

function onMove() {
  w = updateVector(w, true);
  drawLine(line, "#000000", p0, p1);
  var iv = getIntersectVector(cv, w);
  var ccpx = cc.x - iv.vx;
  var ccpy = cc.y - iv.vy;
  iv = updateVector(iv, false);
  var pen = cv.r - iv.len;
  if (pen > 0) {
    circle.alpha = .5;
    drawLine(bl, "#00FF00", cc, {
      x: cc.x + iv.dx * pen,
      y: cc.y + iv.dy * pen
    });
  } else {
    bl.graphics.clear();
    circle.alpha = 1;
  }
  console.log(iv.vx, iv.vy);
  drawLine(il, "#000000", cc, {
    x: ccpx,
    y: ccpy
  });
}

p0.on("pressmove", function(evt) {
  p0.x = evt.stageX;
  p0.y = evt.stageY;
  onMove();
});

p1.on("pressmove", function(evt) {
  p1.x = evt.stageX;
  p1.y = evt.stageY;
  onMove()
});

onMove();