如何保存函数的输出?

时间:2017-11-17 21:26:49

标签: javascript html function

我的网站有一个圆圈,当你点击它时会随机改变颜色。

var letter = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];

function color() {
  lineOfLetters = letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)];
  var colorNumber = "#" + lineOfLetters;
  return colorNumber;
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 250

ctx.beginPath();
ctx.arc(300, 300, 250, 0, 2 * Math.PI, false)

function fillCircle() {
  ctx.fillStyle = color();
  ctx.fill()
}
document.write(color())
.button {
  width: 500px;
  height: 500px;
  background-color: red;
  border-radius: 50%;
  display: inline-block;
  opacity: 0;
  position: absolute;
  left: 58px;
  top: 58px;
}
<body onload="fillCircle()">
  <div onclick="fillCircle()" class="button"></div>
  <canvas id="myCanvas" width="600" height="600">nope</canvas>

</body>

我在页面上准确显示圆圈的颜色。

我试过了:

document.write(color())

但是这只会生成另一个颜色值,并且根本不与圆的颜色相关。

如何让页面准确显示圆圈的颜色?

2 个答案:

答案 0 :(得分:4)

color()的结果分配给变量,然后将其放入DOM中。

var letter = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];

function color() {
  lineOfLetters = letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)];
  var colorNumber = "#" + lineOfLetters;
  return colorNumber;
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 250

var colorSpan = document.getElementById("colorCode");

ctx.beginPath();
ctx.arc(300, 300, 250, 0, 2 * Math.PI, false)

function fillCircle() {
  var c = color();
  ctx.fillStyle = c;
  ctx.fill();
  colorSpan.textContent = c;
}
.button {
  width: 500px;
  height: 500px;
  background-color: red;
  border-radius: 50%;
  display: inline-block;
  opacity: 0;
  position: absolute;
  left: 58px;
  top: 58px;
}
<body onload="fillCircle()">
  <div onclick="fillCircle()" class="button"></div>
  <canvas id="myCanvas" width="600" height="600">nope</canvas>
Color code is <span id="colorCode"></span>
</body>

答案 1 :(得分:1)

只需显示生成的颜色:

function fillCircle (){
    document.write( ctx.fillStyle = color() );
    ctx.fill();
}

但是这里不应该使用 document.write ,你应该添加一个html元素,例如:

 <span id="color" > </span>

所以我们可以在代码

中执行此操作
const colorLabel = document.getElementById("color");

function fillCircle (){
    colorLabel.textContent = ctx.fillStyle = color();
    ctx.fill();
}

旁注:要获得一个6字符的十六进制字符串,您可以轻松完成:

const color = "#" + Math.floor( Math.random() * 16 ** 6 ).toString(16);
相关问题