js-在canvas上绘制圣诞树

本文介绍了如何使用HTML5CanvasAPI在网页上绘制图形,并实现鼠标点击时对特定区域(三角形和矩形)进行填充颜色的交互功能。
摘要由CSDN通过智能技术生成

鼠标点击填充颜色

<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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柠檬鸡腿baiAries_0224

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值