鼠标点击填充颜色
<html>
<head>
<title>Canvas绘制图形</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function drawTriangle(x1, y1, x2, y2, x3, y3) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.closePath();
ctx.stroke();
}
function drawRectangle(x, y, width, height) {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.stroke();
}
function drawGreenTriangle(x1, y1, x2, y2, x3, y3) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.closePath();
ctx.fillStyle = 'green';
ctx.fill();
}
function drawGreenRectangle(x, y, width, height) {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fillStyle = 'brown';
ctx.fill();
}
var triangles = [
{ x1: 100, y1: 100, x2: 150, y2: 20, x3: 200, y3: 100 },
{ x1: 100, y1: 200, x2: 150, y2: 100, x3: 200, y3: 200 }
];
var rectangle = { x: 125, y: 200, width: 50, height: 150 };
function drawShapes() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
triangles.forEach(function(triangle) {
drawTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3);
});
drawRectangle(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
drawShapes();
canvas.addEventListener('click', function(event) {
var rect = canvas.getBoundingClientRect();
var mouseX = event.clientX - rect.left;
var mouseY = event.clientY - rect.top;
triangles.forEach(function(triangle) {
if (
(mouseX >= Math.min(triangle.x1, triangle.x2, triangle.x3)) &&
(mouseX <= Math.max(triangle.x1, triangle.x2, triangle.x3)) &&
(mouseY >= Math.min(triangle.y1, triangle.y2, triangle.y3)) &&
(mouseY <= Math.max(triangle.y1, triangle.y2, triangle.y3))
) {
drawGreenTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3);
}
});
if (
(mouseX >= rectangle.x) &&
(mouseX <= (rectangle.x + rectangle.width)) &&
(mouseY >= rectangle.y) &&
(mouseY <= (rectangle.y + rectangle.height))
) {
drawGreenRectangle(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
});
</script>
</body>
</html>