如何在java脚本中定义的图像中添加事件监听器,这样如果用户点击图像,它将被重定向到其他HTML页面?我正在使用canvas元素。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="1000"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.strokeRect(188,50,237,473); //This is for generating outer rectangle
context.fillStyle="FFFFFF";
context.fillRect(188,50,237,473);
context.strokeRect(200,90,213,365); //This is for generating the inner rectangle
context.fillStyle="grey";
context.fillRect(200,90,213,365);
context.strokeRect(284,50,40,5); //This is for generating small notch at top
context.fillStyle="grey";
context.fillRect(284,50,40,5);
var leftArrow = new Image();
leftArrow.addEventListener('load', eventleftArrowLoaded , false);
leftArrow.src = "leftArrow.jpg";
function eventleftArrowLoaded() {
drawScreen();
}
function drawScreen() {
context.drawImage(leftArrow, 218, 482);//leftArrow
}
</script></body></html>
答案 0 :(得分:0)
图像只是一个离屏位图,其像素内容恰好已复制到画布中。它无法接收事件,因为它不存在于DOM中。
您需要将click
事件侦听器添加到画布,而不是图像:
canvas.addEventListener('click', myfunc, false);
如果您希望确保只有图像覆盖区域内的点击指向新页面,您需要检查鼠标点击坐标。