问:HTML5 Canvas 改变背景颜色

新手上路,请多包涵

我只是想知道是否可以更改 Canvas 颜色 function call ?我有这个代码里面有圆圈我想改变外部颜色(背景):

 var canvads = document.getElementById('canvas')
var context = canvas.getContext('2d');

function circle() {
  var centerX = 0;
  var centerY = 0;
  var radius = 78;
  context.clearRect(0, 0, window.innerWidth,window.innerHeight);

  context.fillStyle = 'rgba(0,0,0,0.5)';
  context.fillRect(0,0,window.innerWidth,window.innerHeight);

  context.translate(canvas.width / 2, canvas.height / 2);

  context.scale(1.5, 2);

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 5 * Math.PI, false);

  context.lineWidth = 5;
  context.stroke();

  context.fillStyle = 'rgba(0,0,0,1)';

  context.globalCompositeOperation = 'destination-out';
  context.fill();

  context.globalCompositeOperation = 'source-over';
}

function change_color() {
  context.fillStyle = 'rgba(0,255,0,1)';
  context.fill();
}

circle()

JsFiddle

原文由 user2808421 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.6k
2 个回答

您需要做的是稍微改变一下方法——尽管在某种程度上可以“填充背景”,但画布的主要工作方式是不断重绘整个图像。在 HTML 游戏中,它每秒完成 X 次,但在较小的项目中,它通常应该在每个动作之后完成。所以,在你的情况下,这样的事情应该可以解决问题: FIDDLE

 var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');

function initCanvas() {
  context.clearRect(0, 0, window.innerWidth,window.innerHeight);

  context.fillStyle = 'rgba(0,0,0,0.5)';
  context.fillRect(0,0,window.innerWidth,window.innerHeight);
}

function circle() {
  var centerX = 0;
  var centerY = 0;
  var radius = 78;

  context.save()
  context.translate(canvas.width / 2, canvas.height / 2);

  context.scale(1.5, 2);

  // define the arc path
  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 5 * Math.PI, false);

  // stroke it
  context.lineWidth = 5;
  context.stroke();

  // make alpha solid (the color doesn't matter)
  context.fillStyle = 'rgba(0,0,0,1)';

  // change composite mode and fill
  context.globalCompositeOperation = 'destination-out';
  context.fill();
  context.restore()

  // reset composite mode to default
}

function changeColor() {
  context.fillStyle = 'rgba(0,255,0,1)';
  context.fillRect(0,0,window.innerWidth,window.innerHeight);

  circle()
}

initCanvas()
circle()
document.querySelector('#but').addEventListener('click',changeColor)

并注意保存/恢复,尤其是在变换/旋转之后。此外,修复了 onclick。

原文由 Michał Sałaciński 发布,翻译遵循 CC BY-SA 4.0 许可协议

设置您使用的画布元素背景颜色

canvas.style.background = "red";  // a valid CSS colour.

你正在用透明颜色填充画布,如果你想要一种颜色是元素背景颜色和透明填充的结果,你需要计算正确的背景颜色,当组合时会给你你想要的颜色。

为了帮助这个答案显示如何计算混合色。 匹配 DOM 颜色混合

原文由 Blindman67 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题