HTML5画布随机不透明度问题

HTML5画布随机不透明度问题,html,canvas,opacity,Html,Canvas,Opacity,有人能给我解释一下为什么这是失败的吗 尝试将不透明度作为随机值加载 我无法将其渲染为除黑色以外的任何颜色,即使警报清楚地显示我得到的值介于0.00和1.00之间 重要代码: 警报(Math.round(Math.random()*100)/100) 不能将Math.random()的javascript放在CSS样式字符串中。这需要连接到字符串 尝试: 不,这绝对是0-1,因为“+varName+”工作得很好。顺便说一句,在这里找到了类似的主题。请注意转发:你在我编辑我的答案的同时发表评论是巧合

有人能给我解释一下为什么这是失败的吗

尝试将不透明度作为随机值加载

我无法将其渲染为除黑色以外的任何颜色,即使警报清楚地显示我得到的值介于0.00和1.00之间

重要代码:


警报(Math.round(Math.random()*100)/100) 不能将Math.random()的javascript放在CSS样式字符串中。这需要连接到字符串

尝试:


不,这绝对是0-1,因为“+varName+”工作得很好。顺便说一句,在这里找到了类似的主题。请注意转发:你在我编辑我的答案的同时发表评论是巧合。要么将我的问题标记为已回答,要么说你自己已回答,但请关闭该问题。可能的副本
    <!DOCTYPE html>
<html>
 <head>
  <script type="application/javascript">

//Names must match each element in your html file
var shapeName = new Object();

shapeName = {sWidth: 50, sHeight: 50, nShapes: 3, bSpacing: 10};

function getHeight(){
    return  document.getElementById("canvas1").offsetHeight;
}

function getWidth(){
    return document.getElementById("canvas1").offsetWidth;
}

function draw() {
 //grabbing the height and width of canvas, note that border is effected by this(ex. width of 400 with border 1 will result 402)
 var cWidth = document.getElementById("canvas1").offsetHeight;
 var cHeight = document.getElementById("canvas1").offsetHeight;

 var canvas = document.getElementById("canvas1");
 var ctx = canvas.getContext("2d");
 alert(Math.round(Math.random() * 100) / 100);
 ctx.fillStyle = "rgba(0, 0, 0, Math.round(Math.random() * 100) / 100)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);

 ctx.fillStyle = "rgba(0, 0, 300, 1.0)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2 + 60, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);

 ctx.fillStyle = "rgb(0,200,0)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2 + 120, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);

 ctx.fillStyle = "rgb(222,25,0)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2 + 180, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);
}
  </script>
 </head>
 <body onload="draw()">
   <canvas id="canvas1" width="400" height="300" style="border: 1px solid;"></canvas>
</body>
</html>
ctx.fillStyle = "rgba(0, 0, 0, " + Math.random() + ")";