我第一次使用HTML5,正在尝试这个 HTML5画布教程。
我已经更改了示例以包括4张图片,并希望在点击事件之前能够检测到点击的是哪张图片。
以下是目前的代码,有人可以告诉我如何在单击事件中检测到已单击的图像吗?另外,mouseout事件似乎并不总是调整图像大小,有任何想法原因吗?
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 0px;
}
</style>
<script src="http://www.html5canvastutorials.com/libraries/kinetic2d-v1.0.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
function initRectangles(rectangles){
// initialize an array of rectangles that provide
// rectangular paths and properties for the images
return [{
name: "buffalo",
image: null,
x: 40,
y: 45,
width: 80,
height: 80,
scale: 1
}, {
name: "indianapolis",
image: null,
x: 125,
y: 45,
width: 80,
height: 80,
scale: 1
}, {
name: "miami",
image: null,
x: 210,
y: 45,
width: 80,
height: 80,
scale: 1
}, {
name: "nyjets",
image: null,
x: 295,
y: 45,
width: 80,
height: 80,
scale: 1
}];
}
function loadImages(sources, callback){
var images = {};
var loadedImages = 0;
var numImages = 0;
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function(){
if (++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
function mapImages(rectangles, images){
// map images to rectangles
var counter = 0;
for (var img in images) {
rectangles[counter++].image = images[img];
}
}
function initStage(images){
var rectangles = initRectangles(rectangles);
mapImages(rectangles, images);
kin = new Kinetic_2d("myCanvas");
var context = kin.getContext();
kin.setDrawStage(function () {
this.clear();
var mousePos = kin.getMousePos();
for (var n = 0; n < rectangles.length; n++) {
var rect = rectangles[n];
context.save();
context.translate(rect.x, rect.y);
context.scale(rect.scale, rect.scale);
kin.beginRegion();
var rectX = -1 * rect.width / 2;
var rectY = -1 * rect.height / 2;
context.drawImage(rect.image, rectX, rectY, rect.width, rect.height);
context.beginPath();
context.rect(rectX, rectY, rect.width, rect.height);
context.closePath();
this.addRegionEventListener("mouseover", function () {
document.body.style.cursor = "pointer";
rectangles[n].scale = 1.07;
});
this.addRegionEventListener("mouseout", function () {
document.body.style.cursor = "default";
rectangles[n].scale = 1;
});
this.closeRegion();
context.restore();
}
});
}
window.onload = function(){
var sources = {
buffalo: "buffalo.png",
indianapolis: "indianapolis.png",
miami: "miami.png",
nyjets: "nyjets.png"
};
loadImages(sources, initStage);
$("#myCanvas").click(function (e) {
});
};
</script>
</head>
<body>
<canvas id="myCanvas" width="400" height="90">
</canvas>
</body>
</html>
kin.setDrawStage()
的for
循环中添加this.addRegionEventListener("click", function () {});
。 - ComFreek