这是我的脚本代码..。
<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()函数的。我画帆布,在画布上画行星。请参考图片。这是运行映像的javascript的时候。有一个地球,水星,金星。那颗行星就是我认为的全部object....If ..。
当用户单击“地球”物体时,我想单击事件。但我不知道怎么做.我该指什么呢?请告诉我..!谢谢。
发布于 2017-04-17 12:36:01
你不能真的。当你在画布上画画时,你实际上是在画一个大的位图图像。你画的形状会加到上面,就这样。它们并不是真正的物体。
你有两个选择:
click事件,获取鼠标坐标,并使用该坐标推断单击了哪个对象。发布于 2017-04-17 12:35:25
你基本上要跟踪你的行星在帆布上的位置,然后在画布上设置一个事件监听器。从那里你可以获得点击事件的坐标,并通过你所有的行星进行测试。
HTML:
<form id="myCanvas" ... >
</form>获取画布元素:
var Earth = document.getElementById('myCanvas');若要向画布元素添加单击事件,请使用.
Earth.addEventListener('click', function() { }, false);查看这示例中有关@Brother说的信息
https://stackoverflow.com/questions/43451471
复制相似问题