【问题标题】:HTML 5 canvas random opacity issueHTML 5 画布随机不透明度问题
【发布时间】:2011-03-13 15:00:00
【问题描述】:

有人可以向我解释为什么会失败。

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

即使警报清楚地显示我正在获取介于 0.00 和 1.00 之间的值,我也无法将其渲染为黑色

重要代码:

alert(Math.round(Math.random() * 100) / 100);

ctx.fillStyle = "rgba(0, 0, 0, Math.round(Math.random() * 100) / 100)";

测试: 1.将不透明度设置为0-1之间的随机变量效果很好 2. 添加上面的警告框只是为了查看范围是否可以接受

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

【问题讨论】:

标签: html canvas opacity


【解决方案1】:

您不能将 Math.random() 的 javascript 放在 CSS 样式字符串中。这需要连接到字符串。

试试:

ctx.fillStyle = "rgba(0, 0, 0, " + Math.random() + ")";

【讨论】:

  • 不,绝对是 0 - 1,因为“+varName+”工作得很好,顺便说一句在这里找到了类似的主题请注意转发:stackoverflow.com/questions/1957346/…
  • 巧合的是,您在我编辑答案的同时发表了评论。将我的问题标记为已回答,或者说您自己回答了,但请关闭问题。
猜你喜欢
  • 2015-01-12
  • 1970-01-01
  • 2010-09-25
  • 2018-02-19
  • 2011-10-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
相关资源
最近更新 更多