我想更改按钮的颜色,然后按画布内的文本颜色更改。
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.font = '48px serif';
context.fillStyle = 'red'; // sets text color to red
context.fillText('Example text', 20, 65);
function ChangeColor() {
console.log("dd", context);
context.fillStyle = "blue";
}
<!doctype html>
<html>
<head>
<style>
#my-canvas {
border: 1px solid gray;
}
</style>
</head>
<body>
<canvas id="my-canvas" width="300" height="100"></canvas>
<br>
<button onClick="ChangeColor()"> Change Font Color Blue</button>
</body>
</html>
您需要清除画布并使用
"blue"
颜色重新绘制所有内容。
您可以使用
清除画布context.clearRect(0, 0, canvas.width, canvas.height);
这是您的用例的工作示例:
const canvas = document.querySelector('#my-canvas');
const context = canvas.getContext('2d');
draw("red");
function ChangeColor() {
clearCanvas();
draw("blue");
}
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function draw(color) {
context.font = '48px serif';
context.fillStyle = color; // sets text color to whatever was passed in
context.fillText('Example text', 20, 65);
}
<!doctype html>
<html>
<head>
<style>
#my-canvas {
border: 1px solid gray;
}
</style>
</head>
<body>
<canvas id="my-canvas" width="300" height="100"></canvas>
<br>
<button onClick="ChangeColor()"> Change Font Color Blue</button>
</body>
</html>