简体   繁体   English

单击按钮更改 canvas 填充颜色

[英]Change canvas fill color on button click

I have an HTML canvas element that a user can draw on, and I want to change the fill color of the canvas when the refresh icon is clicked, and it set it to a different color depending on the body ID.我有一个用户可以绘制的 HTML canvas 元素,我想在单击刷新图标时更改 canvas 的填充颜色,并根据主体 ID 将其设置为不同的颜色。

Currently the onClick function is changing the body ID and body color as a result but it is not updating the canvas fill color.目前 onClick function 正在更改主体 ID 和主体颜色,但它不会更新 canvas 填充颜色。 Does anyone have any ideas.有没有人有任何想法。

I'm fairly new to HTML canvas and not really used it much before so any help is appreciated.我对 HTML canvas 还很陌生,之前并没有真正使用过它,所以感谢任何帮助。

I think it is this bit of code that is wrong.我认为这是错误的代码。

function refresh() {    
  const colors = ["blue", "red", "green", "pink"];  
  const random = Math.floor(Math.random() * colors.length);
  document.body.id = colors[random];
  
  var bodyid = document.body.id;
  console.log(bodyid);
  var bridge = document.getElementById("canvas"),
      bridgeCanvas = bridge.getContext('2d');
  
  if(bodyid  == 'red'){
    bridgeCanvas.fillStyle = "#6ecbff";
  } else if(bodyid  == 'blue') {
    bridgeCanvas.fillStyle = "#fedcdb";
  } else if(bodyid  == 'green') {
    bridgeCanvas.fillStyle = "#fefd55";
  } else if(bodyid  == 'pink') {
    bridgeCanvas.fillStyle = "#96b6cd";
  }
};

The full code is in the codepen below完整代码在下面的codepen中

https://codepen.io/oddpandadesign/pen/vYyybQG https://codepen.io/oddpandadesign/pen/vYyybQG

You have to set the color first and then fill the rectangle.您必须先设置颜色,然后填充矩形。

bridgeCanvas.fillStyle = color;
bridgeCanvas.fillRect(0, 0, bridge.width, bridge.height);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM