gpt4 book ai didi

javascript - 如何单击使用 javascript Canvas 中的对象的事件?

转载 作者:行者123 更新时间:2023-12-03 04:32:01 25 4
gpt4 key购买 nike

这是我的脚本代码..

<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()函数启动。我画 Canvas ,并在 Canvas 上显示行星。请引用图片。 This is when javascript on running image.他们有地球、水星、金星。那颗行星全是物体……如果我认为……

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

最佳答案

你不能,真的。当您在 Canvas 上绘图时,您实际上是在绘制一张大的位图图像。您绘制的形状会添加到其中,仅此而已。它们实际上并不是物体。

您有两个选择:

  1. 从 canvas 元素捕获 click 事件,获取鼠标坐标并使用它来推断哪个对象被单击。
  2. 使用类似 EaselJS 的库。它是一种围绕 Canvas 的 API,使使用它变得更加容易。它将允许您将点击处理程序附加到 Canvas 上的对象。

关于javascript - 如何单击使用 javascript Canvas 中的对象的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43451471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com