首页 > 编程语言 >JavaScript简单特效:页面背景颜色在线改变

JavaScript简单特效:页面背景颜色在线改变

时间:2022-10-14 12:46:19浏览次数:49  
标签:特效 canvas 颜色 JavaScript ctx var ById colorValue 页面

基于JavaScript以及canvas实现输入颜色预览以及背景颜色变为输入颜色值的效果。

输入框中默认值为黑色,下方画布显示该颜色。通过输入新的颜色值后,点击【显示颜色】按钮,画布中的二维正方形显示对应的颜色。点击【设为背景颜色】按钮,整个页面背景颜色均采用该颜色。

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    canvas {
      border: medium double #000000;
      margin: 4px;
    }
  </style>
</head>

<body>
  <form action="" method="get">
    请输入颜色编号: <input type="text" id="colorValue"  />
    <input type="button" id="buttonChange" value="显示颜色">
    <input type="button" id="buttonReset" value="设为页面背景色">
  </form>
  <canvas id="canvas" width="100" height="100">
    Your browser doesn't support the <code>canvas</code>element
  </canvas>

  <script>
 
  </script>

</body>

</html>

  参考代码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    canvas {
      border: medium double #000000;
      margin: 4px;
    }
  </style>
</head>

<body>
  <form action="" method="get">
    请输入颜色编号: <input type="text" id="colorValue" value="black" />
    <input type="button" id="buttonChange" value="显示颜色">
    <input type="button" id="buttonReset" value="设为页面背景色">
  </form>
  <canvas id="canvas" width="100" height="100">
    Your browser doesn't support the <code>canvas</code>element
  </canvas>

  <script>
    function ById(id) {
      var result = document.getElementById(id);
      return result;
    }
    var colorValue = ById("colorValue").value;
    var button1 = ById("buttonChange");
    var button2 = ById("buttonReset");
    var bg_Color = document.getElementsByTagName("html")[0];
    var ctx = ById("canvas").getContext("2d");
    ctx.fillStyle = colorValue;
    ctx.fillRect(20, 20, 50, 50);

    button1.onclick = function () {
      var colorValue = document.getElementById("colorValue").value;
      ctx.fillStyle = colorValue;
      ctx.fillRect(20, 20, 50, 50);

    }

    button2.onclick = function () {
      var colorValue = document.getElementById("colorValue").value;
   
      bg_Color.style.backgroundColor = colorValue;
      

    }
  </script>

</body>

</html>

  

 

标签:特效,canvas,颜色,JavaScript,ctx,var,ById,colorValue,页面
From: https://www.cnblogs.com/f6056/p/16789166.html

相关文章