本文介绍了是否已经有针对 AngularJS 的画布绘图指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there already a directive to draw/paint things on a canvas? So you can implement something like Paint or even something bigger like Photoshop etc., but a very basic example would suffice.

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

I haven't found one in my search and if there's already one that is considered best practice I would like to use it. Else I have to implement one myself.

推荐答案

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

Ok I did one and it is actually pretty easy:

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();
      }
    }
  };
});

然后你可以像这样在画布上使用它:

And then you can use it on canvas like this:

<canvas drawing></canvas>

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

Here's a demo on Plunkr: http://plnkr.co/aG4paH

这篇关于是否已经有针对 AngularJS 的画布绘图指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 13:20