是否已经有指令在 Canvas 上绘制/绘画东西?因此,您可以实现诸如Paint或什至更大的诸如Photoshop等之类的东西,但是一个非常基本的示例就足够了。

我没有在搜索中找到一个,如果已经有一个被认为是最佳实践,我想使用它。否则我必须自己实现。

最佳答案

好的,我做了一个,实际上很简单:

app.directive("drawing", function(){
  return {
    restrict: "A",
    link: function(scope, element){
      var ctx = element[0].getContext('2d');

      // variable that decides if something should be drawn on mousemove
      var drawing = false;

      // the last coordinates before the current move
      var lastX;
      var lastY;

      element.bind('mousedown', function(event){
        if(event.offsetX!==undefined){
          lastX = event.offsetX;
          lastY = event.offsetY;
        } else { // Firefox compatibility
          lastX = event.layerX - event.currentTarget.offsetLeft;
          lastY = event.layerY - event.currentTarget.offsetTop;
        }

        // begins new line
        ctx.beginPath();

        drawing = true;
      });
      element.bind('mousemove', function(event){
        if(drawing){
          // get current mouse position
          if(event.offsetX!==undefined){
            currentX = event.offsetX;
            currentY = event.offsetY;
          } else {
            currentX = event.layerX - event.currentTarget.offsetLeft;
            currentY = event.layerY - event.currentTarget.offsetTop;
          }

          draw(lastX, lastY, currentX, currentY);

          // set current coordinates to last one
          lastX = currentX;
          lastY = currentY;
        }

      });
      element.bind('mouseup', function(event){
        // stop drawing
        drawing = false;
      });

      // canvas reset
      function reset(){
       element[0].width = element[0].width;
      }

      function draw(lX, lY, cX, cY){
        // line from
        ctx.moveTo(lX,lY);
        // to
        ctx.lineTo(cX,cY);
        // color
        ctx.strokeStyle = "#4bf";
        // draw it
        ctx.stroke();
      }
    }
  };
});

然后您可以像下面这样在 Canvas 上使用它:
<canvas drawing></canvas>

这是关于Plunkr的演示:http://plnkr.co/aG4paH

关于html - 那里已经有用于AngularJS的 Canvas 绘制指令了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16587961/

10-11 00:00