使用画布正方形和三角形与自定义颜色当点击bottton [英] using canvas drawing square and triangle with customize color when click bottton

查看:202
本文介绍了使用画布正方形和三角形与自定义颜色当点击bottton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

我有一个问题,这个问题,我想当用户选择颜色,

I have a problem on this question, I want when the user choose the color and click on square or triangle, it will draw it with the color that he/she choose, what should I change and add ?

推荐答案

您需要使用用实际绘制三角形的方法替换第二个 rect(...)调用,你可以通过访问它的 value 属性。

You need to replace the second rect(...) call with something that actually draws a triangle, and you can easily get the color from the input field by accessing its value attribute.

Click here for my fork of your jsFiddle.

访问输入值的相关行如下:

The relevant lines for accessing the input value are here:

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

现在,对于三角形绘图(假设您想要一个等腰三角形适合原始矩形) p>

Now for the triangle drawing (assuming you wanted an isosceles triangle to fit the original rectangle):

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

这篇关于使用画布正方形和三角形与自定义颜色当点击bottton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆