【问题标题】:Drawing a rectangular path in JavaScript [duplicate]在JavaScript中绘制矩形路径[重复]
【发布时间】:2019-06-13 19:27:56
【问题描述】:

我看到,为了绘制矩形路径,您可以使用类似于 here 的公式。

我想知道矩形路径是否有类似的东西?

编辑:我希望能够让一个点逐步绘制出整个矩形路径,而不是只显示整个矩形。

function redraw () {
  // 
     Code for the animation, while keeping track of last point 
    (such that the end animation is continuous)

  //
  clearScreen();
  ctx.beginPath();
  ctx.rect(x,y,5,5);
  ctx.stroke();
}

setInterval(redraw, 16);
redraw();

我也不想使用任何外部库

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    您可以使用 generator function 预先定义动画 - 请原谅糟糕的代码,这只是为了给您一个想法:

    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    
    // here we create a generator function,
    // where we define each step:
    function* rect(ctx, x, y, x2, y2) {  
      // top line
      for (let k = x; k <= x2; k++) {
        ctx.lineTo(k, y);
        yield;
      }
    
      // right line
      for (let j = y; j <= y2; j++) {
        ctx.lineTo(x2, j);
        yield;
      }
    
      // bottom line
      for (let k = x2; k >= x; k--) {
        ctx.lineTo(k, y2);
        yield;
      }
    
      // left line
      for (let j = y2; j >= y; j--) {
        ctx.lineTo(x, j);
        yield;
      }
    }
    
    const steps = rect(ctx, 10, 10, 80, 90);
    ctx.strokeStyle = "black"
    
    function draw () {
      if (!steps.next().done){
        ctx.stroke();
      } else {
        // here the animation is done
        ctx.fill();
      }
    
      // 60 fps
      requestAnimationFrame(draw); 
    }
    
    draw();
    

    【讨论】:

    • 如果您还必须考虑调整大小怎么办?
    • 这真的取决于在动画期间如何调整大小。
    • 对我来说最好的情况是,如果我调整大小,路径上的下一个点将符合新调整大小的窗口。使用圆形,这不会太难,因为我可以保留一个 theta 并将其应用于参数圆形方程,但是如何使用矩形呢?
    • 我的问题是在动画期间“如何”调整大小,如前所述:例如,用户与拖动交互?原产地在哪里?当调整大小发生时,动画会发生什么?会暂停吗?将继续?调整大小是否也会在期间其他动画?所以你会有几个动画。有太多的场景需要考虑给你一个通用的答案。这真的取决于。已经“完成”的行会发生什么?
    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多