Browse Source

Improvements to Canvas and the addition of generators

Bonyant 2 years ago
parent
commit
4c33b4135a
3 changed files with 67 additions and 3 deletions
  1. 14 3
      16/index.js
  2. 12 0
      17/index.html
  3. 41 0
      17/index.js

+ 14 - 3
16/index.js

@@ -209,9 +209,20 @@ class Line extends Drawable {
   }
 
   in(x, y) {
-    // console.log("this.x " + this.x, "this.y " + this.y);
-    // console.log("x " + x, "y " + y);
-    // new Line(this.x, this.y, this.width, 0, "red");
+    let angleCrank = Math.atan2(this.height, this.width);
+    let angleMouse = Math.atan2(y - this.y, x - this.x);
+    let lengthLine = this.distanceTo(this.x + this.width, this.y + this.height);
+    let horizontal = angleMouse - angleCrank;
+    let newX = Math.cos(horizontal) * distance(x, y, this.x, this.y);
+    let newY = Math.sin(horizontal) * distance(x, y, this.x, this.y);
+    if (
+      newX > 0 &&
+      newX < lengthLine &&
+      newY > this.lineWidth / -2 &&
+      newY < this.lineWidth / 2
+    ) {
+      console.log("selected");
+    }
   }
 }
 

+ 12 - 0
17/index.html

@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>JavaScript Generators</title>
+  </head>
+  <body>
+    <script src="index.js"></script>
+  </body>
+</html>

+ 41 - 0
17/index.js

@@ -0,0 +1,41 @@
+function* likeFor(end, step = 1, start = 0) {
+  for (let i = start; i < end; i += step) {
+    yield i;
+  }
+}
+
+function* twice() {
+  yield* gena(10);
+  yield* gena(20);
+}
+
+const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
+
+function* likeAsync() {
+  console.log(1);
+  let res1 = yield delay(2000);
+  console.log(2, res1);
+  let res2 = yield delay(2000);
+  console.log(3, res2);
+}
+
+function run(likeAsync) {
+  let iter = likeAsync();
+  function next(result, err) {
+    let value, done;
+    if (!err) {
+      [{ value, done }] = [iter.next(result)];
+    } else {
+      [{ value, done }] = [iter.throw(err)];
+    }
+    if (done) return;
+    if (value && typeof value?.then === "function") {
+      value.then(next, (err) => next(undefined, err));
+    } else {
+      next(value);
+    }
+  }
+  next();
+}
+
+run(likeAsync);