Raxkin
Raxkin

Reputation: 397

onmouse Canvas HTML5

I am tryng to draw a path of my mouse on a canvas but i dont know what is is wrong but it dont draw anything. It works fine withcontext.fillRect() but not whit ImageData. This is my code:

<!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>

Upvotes: 2

Views: 115

Answers (1)

Daniel Kopitchinski
Daniel Kopitchinski

Reputation: 525

You'll want to use

canvasData.data[index + 3] = 255;

Instead of

canvasData.data[index + 3] = 1;

While the canvas fillStyle uses an alpha value between 0-1, when you want to actually update the raw data for the canvas, alpha values are ranged between 0 and 255.

Upvotes: 3

Related Questions