- Create a canvas element on the HTML page.
- Use JavaScript to draw a triangle and fill it. You can use canvas APIs to draw shapes, such as beginPath() and lineTo() etc.
- Bind an event listener to the canvas element to fire when the triangle is clicked. You can use addEventListener() function for this purpose.
- Add required logic in event handlers, such as popping up a message or changing an element on the page.
Sample code:
<!DOCTYPE html>
<html>
<head>
<title>Draw Triangle on Canvas</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// 画一个三角形
context.beginPath();
context.moveTo(100, 100);
context.lineTo(200, 100);
context.lineTo(150, 200);
context.closePath();
context.fillStyle = '#0095DD';
context.fill();
// 添加事件监听器
canvas.addEventListener('click', function(event) {
var x = event.pageX - canvas.offsetLeft;
var y = event.pageY - canvas.offsetTop;
if (context.isPointInPath(x, y)) {
alert('你点击了三角形!');
}
});
</script>
</body>
</html>
In the above code, we draw a triangle using the Canvas API and add event listeners inside it. When the triangle is clicked, we check to see if the mouse click was inside the triangle and display a message in a popup.