html JS.Interact.MouseonCanvas.Ex3

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html JS.Interact.MouseonCanvas.Ex3相关的知识,希望对你有一定的参考价值。

canvas {
  border:1px solid black
}
var canvas, ctx, mousePos, mouseButton;

window.onload = function init() {
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');

    canvas.addEventListener('mousemove', function (evt) {
        mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
    }, false);

      canvas.addEventListener('mousedown', function (evt) {
        mouseButton = evt.button;
        var message = "Mouse button " + evt.button + " down at position: " + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
    }, false);

    canvas.addEventListener('mouseup', function (evt) {
        var message = "Mouse up at position: " + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
    }, false);
};



function writeMessage(canvas, message) {
    ctx.save();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.font = '12pt Calibri';
    ctx.fillStyle = 'black';
    ctx.fillText(message, 10, 25);
    ctx.restore();
}

function getMousePos(canvas, evt) {
    // necessary to take into account CSS boudaries
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}




JS.Interact.MouseonCanvas.Ex3
-----------------------------


A [Pen](https://codepen.io/Onlyforbopi/pen/wEbGXK) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).

[License](https://codepen.io/Onlyforbopi/pen/wEbGXK/license).
<!DOCTYPE HTML>
<html lang="en">
  <head>
<!----
A good example that shows how to display the mouse position, and the mouse button that has been pressed or released
This example uses the previous function for computing the mouse position correctly. It listens to mousemove, mousedown and mouseup events, and shows how to get the mouse button number using the evt.button property.


-->
    

    <title>Wrong way to get the mouse
    position in a canvas</title>
    <meta charset="utf-8">
    <style>
      body {
        margin: 20px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
   <p> Move the mouse cursor and click anywhere!</p>
    <canvas id="myCanvas" width="300" height="200"></canvas>
  </body>
</html>

以上是关于html JS.Interact.MouseonCanvas.Ex3的主要内容,如果未能解决你的问题,请参考以下文章

html Html模板/ Html Boilerplate |标签HTML

html里怎么引用一个html的头部

html5与传统html区别

html4和html5的区别

HTML元素

head标签怎么给多个html引用