在电脑课上,我不得不画一些我喜欢的东西,所以我决定画m&ms。然而,它在糖果上写的“m”与糖果的颜色相同,而不是白色。这是我的一个m&m代码:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function drawCircle(x, y, rad, cut, pi, color) {
  ctx.beginPath();
  ctx.arc(x, y, rad, cut, Math.PI * pi);
  ctx.closePath();
  ctx.fillStyle = color;
  ctx.fill();

}

function drawMnM(x, y, color) {
  drawCircle(x, y, 15, 0, 2, color);
  ctx.font = "30px Arial";
  ctx.fillText("m", x - 15, y);
  ctx.fillStyle = "white";
}

drawMnM(75, 75, "red");

<canvas id="myCanvas" style="border:1px solid #d3d3d3;">
    </canvas>

m&m的“m”显示为红色,所以我如何解决这个问题?

最佳答案

您需要在fillStyle之前设置fillText(因为它将用于绘制文本)

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function drawCircle(x, y, rad, cut, pi, color) {
  ctx.beginPath();
  ctx.arc(x, y, rad, cut, Math.PI * pi);
  ctx.closePath();
  ctx.fillStyle = color;
  ctx.fill();

}

function drawMnM(x, y, color) {
  drawCircle(x, y, 15, 0, 2, color);
  ctx.font = "30px Arial";
  ctx.fillStyle = "white";
  ctx.fillText("m", x - 15, y);
}

drawMnM(75, 75, "red");

<canvas id="myCanvas"  style="border:1px solid #d3d3d3;">
    </canvas>

关于javascript - 在Javascript上绘制两种不同的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43191949/

10-12 00:46
查看更多