onmouse Canvas HTML5

时间:2014-11-16 22:44:27

标签: javascript html5 canvas

我试图在画布上绘制鼠标的路径,但我不知道什么是错的,但它不会画任何东西。它适用于context.fillRect(),但不适用于ImageData。这是我的代码:

<!DOCTYPE HTML>
<html>
  <head>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="600" style=" border-style: solid;"></canvas>
    <script>

        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var canvasWidth = canvas.width;
        var canvasHeight = canvas.height;
        var canvasData = context.getImageData(0, 0, canvasWidth, canvasHeight);

        function drawPixel(x, y) {
            var index = (x + y * canvasWidth) * 4;

            canvasData.data[index] = 0; //Red
            canvasData.data[index + 1] = 255; //Green
            canvasData.data[index + 2] = 0; //Blue
            canvasData.data[index + 3] = 1; //Alpha
        }

        function updateCanvas() {
            context.putImageData(canvasData, 0, 0);
        }

      function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: Math.round((evt.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
          y: Math.round((evt.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
        };
      }

      canvas.addEventListener('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        drawPixel(mousePos.x,  mousePos.y);
        updateCanvas();
      }, false);
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:3)

你想要使用

canvasData.data[index + 3] = 255;

而不是

canvasData.data[index + 3] = 1;

虽然画布fillStyle使用0-1之间的alpha值,但当您想要实际更新画布的原始数据时,alpha值的范围介于0到255之间。