【问题标题】:using canvas drawing square and triangle with customize color when click bottton单击按钮时使用画布绘制具有自定义颜色的正方形和三角形
【发布时间】:2013-01-03 07:56:08
【问题描述】:

我有以下代码:

<html>
 <head>


 </head>
 <body>
    <canvas id="canvasId" width="300" height="300"></canvas>
    <script>
function square() {

  var ctx = document.getElementById('canvasId').getContext('2d');
  var col= document.getElementById("clr");
      ctx.beginPath();
      ctx.rect(10, 10, 70, 70);
      ctx.fillStyle = 'yellow';
      ctx.fill();
      ctx.lineWidth = 2;
      ctx.strokeStyle = 'black';
      ctx.stroke();

}
function triangle () {

      var canvas = document.getElementById('canvasId');
      var context = canvas.getContext('2d');
        var col= document.getElementById("clr");
      context.beginPath();
      context.rect(85, 80, 200, 100);
      context.fillStyle = 'yellow';
      context.fill();
      context.lineWidth = 2;
      context.strokeStyle = 'black';
      context.stroke();

}

    </script>
  <p>Color <input type="color" id="clr" value="" /></p>
  <input type="button" value="square" onclick="square()" />
  <input type="button" value="triangle" onclick="triangle()" />
 </body>
</html>

我对这个问题有疑问,我想当用户选择颜色并点击正方形或三角形时,它会用他/她选择的颜色绘制它,我应该更改和添加什么?

【问题讨论】:

    标签: canvas html5-canvas


    【解决方案1】:

    您需要将第二个rect(...) 调用替换为实际绘制三角形的内容,并且您可以通过访问其value 属性轻松地从输入字段中获取颜色。

    Click here for my fork of your jsFiddle.

    访问输入值的相关行在这里:

    var col= document.getElementById("clr");
    ctx.fillStyle = col.value;
    

    现在绘制三角形(假设您想要一个等腰三角形来适应原始矩形):

    context.beginPath();
    context.moveTo(85, 180);
    context.lineTo(185, 80);
    context.lineTo(285, 180);
    context.closePath();
    

    【讨论】:

      【解决方案2】:

      我在http://jsfiddle.net/rcondori/3gmosgq7/有一个例子

      这个例子是梯形的...

      function isInsideBox(x, y, x1, x2, y1, y2) {
      var a = getValueA(x1, x2, y1, y2);
      var b = getValueB(x1, y1, a);
      var auxY = (a * x) + b;
      if (auxY <= y) {
          return true;
      } else {
          return false;
      }
      }
      function getValueA(x1, x2, y1, y2) {
      return ((y1 - y2) / (x1 - x2));
      }
      function getValueB(x1, y1, a) {
      return (y1 - (a * x1));
      }
      

      【讨论】:

      • 嘿,罗恩,很好的答案,请注意任何使用此问题的人的错误:if (y > element.y1 && y element.x1 && x element.y1 && y element.x1 && x
      猜你喜欢
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 2017-01-13
      相关资源
      最近更新 更多