用表面笔绘制画布

时间:2017-05-19 08:37:10

标签: javascript html5 canvas pointer-events

我目前正在使用此代码使用Microsoft Surface中的笔在画布上绘制(当然,在表面上):

<html>
      <head>
        <style>
          /* Disable intrinsic user agent touch behaviors (such as panning or zooming) */
          canvas {
            touch-action: none;
          }
        </style>


      <script type='text/javascript'>
        var lastPt = null;
        var canvas;
        var ctx;

        function init() {
          canvas = document.getElementById("mycanvas");
          ctx = canvas.getContext("2d");
          var offset  = getOffset(canvas);
          if(window.PointerEvent) {
            canvas.addEventListener("pointerdown", function() {
              canvas.addEventListener("pointermove", draw, false);
            }
            , false);
            canvas.addEventListener("pointerup", endPointer, false);
          }
          else {
            //Provide fallback for user agents that do not support Pointer Events
            canvas.addEventListener("mousedown", function() {
              canvas.addEventListener("mousemove", draw, false);
            }
            , false);
            canvas.addEventListener("mouseup", endPointer, false);
          }
        }

        // Event handler called for each pointerdown event:
        function draw(e) {
          if(lastPt!=null) {
            ctx.beginPath();
            // Start at previous point
            ctx.moveTo(lastPt.x, lastPt.y);
            // Line to latest point
            ctx.lineTo(e.pageX, e.pageY);
            // Draw it!
            ctx.stroke();
          }
          //Store latest pointer
          lastPt = {x:e.pageX, y:e.pageY};
        }

        function getOffset(obj) {
          //...
        }

        function endPointer(e) {
          //Stop tracking the pointermove (and mousemove) events
          canvas.removeEventListener("pointermove", draw, false); 
          canvas.removeEventListener("mousemove", draw, false); 

          //Set last point to null to end our pointer path
          lastPt = null;
        }

      </script>
    </head>
    <body onload="init()">
      <canvas id="mycanvas" width="500" height="500" style="border:1px solid black;"></canvas>
    </body>
  </html>

到目前为止一切顺利,工作正常。

我现在打算做的是画布对表面笔的压力作出反应。

我知道PointerEvent有一个属性pressure,我知道对于canvas,有lineWidth。但是我该如何结合这些呢?因此,当我只是施加一点压力时,我会得到一条细线,压力越大,线条越粗?

由于

编辑:刚才意识到,代码中似乎存在问题,即使使用笔绘图时,似乎也会跳转到其他情况(因此使用鼠标的后备) ,试图在if部分添加console.log,而不打印......为什么会这样?

0 个答案:

没有答案