如何使用鼠标事件旋转线条

时间:2012-04-07 09:17:26

标签: javascript html5 mouseevent

我是html5的新手,我想问一下,有一种方法我可以使用html5 javascript在画布上使用鼠标事件绘制一条线并使其旋转可调整大小。 谢谢

1 个答案:

答案 0 :(得分:1)

这是一个非常简单(但仍在工作!)的例子,可以帮助你入门:

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            window.addEventListener("load",function() {
                //set a reference to the canvas element
                var canv = document.querySelector("canvas");

                //set its width and height to fill the window
                canv.setAttribute("width", window.innerWidth+"px");
                canv.setAttribute("height",window.innerHeight+"px");

                //set a reference to the canvas' 2d drawing context
                var ctx = canv.getContext('2d');

                //now set up the eventListener
                window.addEventListener("mousemove", function(e) {

                    //first clear canvas
                    ctx.moveTo(0,0);
                    ctx.clearRect(0,0,window.innerWidth,window.innerHeight);

                    //move the "pointer" to the middle of the canvas
                    ctx.beginPath();
                    ctx.moveTo(window.innerWidth/2,window.innerHeight/2);

                    //tell it to draw a line from there to the mouse coords
                    ctx.lineTo(e.x,e.y);
                    ctx.stroke();
                });
            });
        </script>
    </head>
    <body>
        <canvas></canvas>
    </body>
</html>

如果您有任何其他问题,请与我们联系。