【问题标题】:How do I click on an event that uses an object in the javascript canvas?如何单击使用 javascript 画布中的对象的事件?
【发布时间】:2017-04-17 20:36:01
【问题描述】:

这是我的脚本代码..

<body onload= "startGame()">
<script>
var Earth;
var Mercury;
var Venus;

function startGame() {
    Earth = new component(152, 183, 'earth.png', 800, 75);
    Mercury = new component(122,151, 'mercury.png', 300, 400);
    Venus = new component(152, 183, 'venus.png', 520, 240);
    GameArea.start();   
}

var GameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 1000;
        this.canvas.height = 642;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas,         document.body.childNodes[0]);

        this.interval = setInterval(updateGameArea, 20);
    },

    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

//make game pieces
function component(width, height, color, x, y) {
    this.type = "image";
    this.image = new Image();
    this.image.src = color;

    this.width = width;   this.height = height;
    this.x = x;           this.y = y;

    this.update = function() {
        ctx = GameArea.context;
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
    }
}

function updateGameArea() {
    GameArea.clear();
    Earth.update();
    Mercury.update();
    Venus.update();
}
</script>
</body>

代码是当浏览器打开时,startGame() 函数被启动。 我绘制画布,并在画布上显示行星。 请参考图片。 This is when javascript on running image. 他们有地球、水星、金星。 那颗星球全是物体……如果我想……

我想在用户点击“地球”对象时点击事件.. 但我不知道该怎么做...... 我应该参考什么? 请给我建议..!谢谢。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你不能,真的。当您在画布上绘图时,您实际上是在绘制一个大的位图图像。您绘制的形状会添加到其中,仅此而已。它们实际上不是对象。

    你有两个选择:

    1. 从 canvas 元素中捕获 click 事件,获取鼠标坐标并使用它来推断单击了哪个对象。
    2. 使用像EaselJS 这样的库。它是一种围绕画布的 API,可以更轻松地使用它。它将允许您将点击处理程序附加到画布上的对象。

    【讨论】:

      【解决方案2】:

      您基本上必须跟踪您的行星在画布上的位置,然后在画布本身上设置一个事件侦听器。从那里您可以获取点击事件的坐标并遍历所有行星进行测试。

      HTML:

      <form id="myCanvas" ... >
      </form>
      

      获取画布元素:

      var Earth = document.getElementById('myCanvas');
      

      要向画布元素添加点击事件,请使用...

      Earth.addEventListener('click', function() { }, false);
      

      查看this 示例,了解@Brother Woodrow 说的信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 2020-01-13
        • 1970-01-01
        • 2017-11-27
        相关资源
        最近更新 更多