我试图用Dropbox中的某些颜色填充矩形画布。 现在,我试图填充画布:白色,红色,蓝色,绿色。单击“添加颜色”按钮时,使用所选颜色填充画布。单击“清除”按钮时,应重置/删除颜色。
到目前为止,我的HTML代码是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="colors.js" type="text/javascript" defer></script>
</head>
<body onload="setUp()">
<h1>Canvas colors</h1>
<p>What colors should fill?
<select>
<option value="white">White</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<button type="button" id="addColor" name="button">Add Color</button>
<button type="button" id="clearColor" name="button">Clear Color</button>
</p>
<br>
<br>
<canvas id="myCanvas" height="300" width="300" style="border: 1px solid black"></canvas>
</body>
</html>
JS:
let canvas;
let ctx;
function setUp(){
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
let addColor = document.getElementById('addColor');
let clearColor = document.getElementById('clearColor');
myCanvas();
}
addColor.onclick = function() {
function myCanvas(){
ctx.fillStyle = ["white", "red", "blue", "green", "pink", "purple", "black", "orange"];
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
}
clearColor.onclick = function() {
function myCanvas(){
ctx.fillStyle = white;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
}
答案 0 :(得分:0)
你的JS代码是完全错误的。
这是一个有效的example
您的错误在于您正在向元素(变量)添加事件处理程序
在addColor
函数关闭内声明了clearColor
和setUp
。
在您的情况下,JS代码应如下所示:
function setUp(){
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
document.getElementById('addColor').onclick = function() {
ctx.fillStyle = document.getElementById('colorSelector').value;
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
document.getElementById('clearColor').onclick = function() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
}