我正在学习JavaScript。 我有这个任务 - 绘制两个矩形,在其中一个,我应该移动光标,它应该出现在第二个矩形。 跟踪光标并不难,我不知道如何在其他地方显示它。 我需要创建单独的画布吗? 如何显示光标图像? 我会非常感谢任何提示!
这是我现在的简单代码:
<html> <body> <canvas id="myCanvas" width="800" height="600" ></canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.rect(20, 20, 300, 200); ctx.stroke(); ctx.rect(350, 20, 300, 200); ctx.stroke(); var cursorX; var cursorY; document.onmousemove = function(e){ cursorX = e.pageX; cursorY = e.pageY; } </script> </body>I am learning JavaScript. And I have this task - to draw two rectangles, in one of them, I should move the cursor, and it should appear in the second rectangle. It is not that hard to track the cursor, bu I have no idea how to display it somewhere else. Do I need to create separate canvas? How to display cursor image? I would be very grateful for any tips!
Here is a simple code that I have for now:
<html> <body> <canvas id="myCanvas" width="800" height="600" ></canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.rect(20, 20, 300, 200); ctx.stroke(); ctx.rect(350, 20, 300, 200); ctx.stroke(); var cursorX; var cursorY; document.onmousemove = function(e){ cursorX = e.pageX; cursorY = e.pageY; } </script> </body>最满意答案
您应该创建一个带有光标的IMG。 然后,当你在一个矩形上进行模拟时,使用img(或包含DIV的)css将其正确地显示在第二个矩形上。 它类似于显示工具提示的方式
function (event) { var x = event.pageX; var y = event.pageY; var mouseImg = document.getElementById('mouseImg'); if (mouseImg ) { $(mouseImg ).css('left',(x + rectangleOffset.x) + 'px'); $(mouseImg ).css('top',y + rectangleOffset.y + 'px'); $(mouseImg ).show(); } }You should create an IMG with a cursor in it. Then, when you are moussing over one rectangle, use the img's (or containing DIV's) css to display it over the second rectangle correctly. It is similar to how you might display a tooltip
function (event) { var x = event.pageX; var y = event.pageY; var mouseImg = document.getElementById('mouseImg'); if (mouseImg ) { $(mouseImg ).css('left',(x + rectangleOffset.x) + 'px'); $(mouseImg ).css('top',y + rectangleOffset.y + 'px'); $(mouseImg ).show(); } }更多推荐
发布评论