javascript - 如何在每次点击移动图形时知道它的宽度和高度?

标签 javascript jquery html canvas

我对一个从屏幕左侧开始到屏幕右上区域结束的移动人物有疑问。

让我们看看。我是这方面的新手。我在 Canvas 和 JS 上做这个,也用 jQuery。我有一个移动的图形,每次我点击它(或 Canvas )都会改变它的颜色。

但我的问题出在以下事情上:当我单击移动对象时,我希望该对象告诉我它的宽度和高度。但是告诉我它的宽度和高度的是 Canvas ,而不是移动的图形。

我该如何改进?我做错了什么?

这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>Moving Figure</title>
    <meta charset="utf-8">
</head>

<body>
    <canvas id="canvas" width="400" height="400" style="border:1px solid #000000"></canvas>

    <script src="https://code.jquery.com/jquery-2.1.0.js"></script>

    <script>

    var color = ['green', 'red', 'blue', 'purple', 'yellow'];
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var posicion = 0;    
    var tamano = 0;

    setInterval(function () {

    ctx.clearRect(0, 0, 400, 400);
    ctx.fillRect(posicion, 0, tamano, 400-tamano);

    posicion++;
    tamano++;

    if (posicion > 400){
        posicion = 0;
        tamano = 0;
        ctx.fillStyle = color[Math.floor(Math.random() * 4)]; 
        }
    }, 30);


    $("#canvas").click(function(){
        ctx.fillStyle = color[Math.floor(Math.random() * 4)];

    $("p").text( "The Width of the figure is " + event.pageX + " and the Height is " + event.pageY);
    });

  </script>
   <p id="texto"></p>
</body>
</html>

提前致谢!

最佳答案

这是因为对于 canvas 的点击事件,项目 event.pageXevent.pageY 将与 Canvas 。尽管您可以计算出图形的宽度和高度,因为您在此处的语句中说明了这一点:

ctx.fillRect(posicion, 0, tamano, 400-tamano);

事件参数是fillRect(x, y, width, height)。所以宽度将为 tamano,高度为 400-tamano:

$("p").text( "The Width of the figure is " + tamano+ " and the Height is " + (400-tamano));

只需点击 Canvas 就会发生这种情况,如果您希望它仅在您点击图形时更新,您可以通过获取 x,y,width,height 进行碰撞检测与鼠标的 mouseX,mouseY 相比的值:

$("#canvas").click(function(e){
    var cRect = canvas.getBoundingClientRect();
    var mouseX = e.clientX - cRect.left;
    var mouseY = e.clientY - cRect.top;        

    var figureX = posicion;
    var figureY = 0;
    var figureW_off = posicion + tamano;
    var figureH_off = 400-tamano;      
    ctx.fillStyle = color[Math.floor(Math.random() * 4)];

    if(mouseX >= figureX && mouseX <= figureW_off &&
       mouseY >= figureY && mouseY <= figureH_off)
    {
        $("p").text( "The Width of the figure is " + tamano+ " and the Height is " + (400-tamano));
    }
});

Fiddle Example

关于javascript - 如何在每次点击移动图形时知道它的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32429643/

相关文章:

html - 如何使用 flexbox 将一个 div 放在另一个之上

javascript - 用于显示和编辑数据的文本框

javascript - 如何更改具有某些特殊 ID 的多 div 显示?

html - Internet Explorer 重定向到 Paypal 不工作

jquery - 需要关于圆 Angular jquery 插件的建议

javascript - 如何用jQuery保存 "title"的 "a"属性?

javascript - 使用ajax设置html5媒体源

javascript - 我在 jquery 中的悬停功能不起作用

javascript - 简单的在线网络游戏最终崩溃

javascript - Pageres (phantomjs) 不返回 promise