我有一个HTML5画布,我在其中添加了一个图像,我想调用图像的点击事件,但事件不会触发。我正在写一个HTML代码和一些jqmobile的代码
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<script src="jquery.mobile-1.2.1.js"></script>
<script src="jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
<canvas id="canvas1" style="position: absolute; left: 0px; top: 0px;" width="1280" height="960">This text is displayed if your browser does not shown.
</canvas>
<script>
$(function () {
var ctx = document.getElementById("canvas1").getContext("2d");
var imgBasket = new Image();
imgBasket.id = "imgBasket";
imgBasket.src = "Basket.png";
ctx.drawImage(imgBasket, 580, 260, 200, 200);
//this jquery mobile event not working in canvas
$("document").on("vclick", "#imgBasket", function () {
alert("Hello");
});
});
</script>
</body>
</html>
答案 0 :(得分:8)
现在我明白了你想要实现的目标,你想在画布中放置一个图像,然后使用jquery来查看你点击图像的时间。好吧,可悲的是,它不会像这样工作。画布中的图像不再是dom元素,只有画布本身就是一个。这意味着您可以致电:
$('#canvas').on('click', function() {});
但你不能打电话
$("document").on("click", "#canvasImage", function () {});
因为#canvasImage不存在,即使原始图像是dom节点。 如果您的项目没有其他方式,那么fabricjs可能有所帮助:
答案 1 :(得分:3)
您不能在画布上绘制的图像或形状上添加eventlistener 所以你必须在你绘制图像的像素上添加eventlistener 例如:
var img=document.getElementById("img1");
//ctx.drawImage(img,x,y,height,width);
ctx.drawImage(img,10,10,20,20);
$("#canvas1").on("click",function(event){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do{
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
//Image x y cordinates adding width and height
if((canvasX>=10 && canvasX<=30) && (canvasY>=10 && canvasY<=30))
{
alert("canvasX:"+canvasX+" "+"canvasY:"+canvasY);
}
});
答案 2 :(得分:1)
图像在画布上绘制,您不能将其视为元素。
你可以像检查点击的坐标一样,如果它位于你的图像上 这是一个样本。
var canvas = document.getElementById("canvas1");
canvas.addEventListener("mousedown", clicked, false);
function clicked(e){
e.preventDefault();
var x = e.clientX;
var y = e.clientY;
if(x>580 && x<780 && y>260 && y>460){ //780 = 580+(200) <- image width
alert('Hello');
}
}
答案 3 :(得分:-1)
似乎缺少点击事件的侦听器。怎么样这样做:
<!DOCTYPE html><html>
<head><title>Canvas HTML5 Test Page</title>
<script>
function newCanvasListen() {
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var imgBasket = new Image();
imgBasket.src = "Basket.png";
imgBasket.id = "imgBasket";
imgBasket.onload = function() {
var imageBasket = ctx.drawImage(imgBasket, 0, 0);
ctx.fillStyle = imageBasket;
};
canvas.addEventListener("mousedown", doMouseDown, false);
}
function doMouseDown(event) {
alert("Hello");
}
</script>
</head>
<body onLoad=newCanvasListen()>
<canvas width="256" HEIGHT="256" ID="canvas1">
This text is displayed if your browser does not shown.
</canvas>
</body>
</html>