在Canvas中的点击功能上设置不同的颜色

问题描述 投票:0回答:1

我想更改按钮的颜色,然后按画布内的文本颜色更改。

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>

javascript html canvas html5-canvas
1个回答
1
投票

您需要清除画布并使用

"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>

© www.soinside.com 2019 - 2024. All rights reserved.