简体   繁体   English

如何使用“输入颜色和 onchange”更改 canvas 背景颜色

[英]How can i change canvas background color with “ input color and onchange ”

My teacher gave me homework, but he didn't explain the details.我的老师给了我作业,但他没有解释细节。 He just said "write JS codes to change canvas background with color input and onChange event".他只是说“编写JS代码以通过颜色输入和onChange事件更改canvas背景”。 So far, I have tried this but I am stuck:到目前为止,我已经尝试过了,但我被卡住了:

<!DOCTYPE html>
<html>
<body>
  <canvas id="canvas1" width="200" height="100"
style="border:1px; background:red ; color:blue ">
</canvas>
<form>
  <input type="button" onclick="myFunction()">
  <input type="color"  onchange="?">

</form>
<script>
function myFunction() {
  document.getElementById('canvas1').style.background = "green";
}
</script>

  </body>
</html>

You're pretty close.你很接近。 What you could do is add a parameter for myFunction which would be a reference of the input to itself, then use that to set the value.您可以做的是为 myFunction 添加一个参数,该参数将作为输入对其自身的引用,然后使用它来设置值。 Here's an example of what I mean:这是我的意思的一个例子:

Change the input to this:将输入更改为:

<input type="color"  onchange="myFunction(this)">

And change the function to this:并将 function 更改为:

function myFunction(self) {
    document.getElementById('canvas1').style.background = self.value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM