关于html5 canvas元素 为什么在chrome和火狐里都显示不了。去掉 if (canvas == null) return false;才行

<html>
<head></head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas')
if (canvas == null)
return false;
var context = canvas.getContext("2d");
//实践表明在不设施fillStyle下的默认fillStyle=black
context.fillRect(0, 0, 100, 100);

//设置纯色
context.fillStyle = "rgba(255,0,0,0.2)";
context.strokeStyle = "blue";
context.fillRect(0, 120, 100, 100);
context.strokeRect(120, 120, 100, 100);

//设置透明度实践证明透明度值>0,<1值越低,越透明,值>=1时为纯色,值<=0时为完全透明

context.fillStyle = "red";

context.fillRect(240,0 , 100, 100);
context.fillStyle = "rgba(255,0,0,0.2)";
context.fillRect(240, 120, 100, 100);
</script>
</body>
</html>

估计你刚学javascript吧,return不能用在“外部”。return需要在“函数内部”。

function test() {
    var canvas = document.querySelector('canvas');
    if (!canvas) alert('浏览器不支持');
    console.log(canvas)
}
test()

 

<html>
<head></head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
function create() {
  var canvas = document.getElementById('myCanvas')
  if (canvas == null) return false;
  var context = canvas.getContext("2d");
  //实践表明在不设施fillStyle下的默认fillStyle=black
  context.fillRect(0, 0, 100, 100);
  //设置纯色
  context.fillStyle = "rgba(255,0,0,0.2)";
  context.strokeStyle = "blue";
  context.fillRect(0, 120, 100, 100);
  context.strokeRect(120, 120, 100, 100);
  //设置透明度实践证明透明度值>0,<1值越低,越透明,值>=1时为纯色,值<=0时为完全透明
  context.fillStyle = "red";
  context.fillRect(240,0 , 100, 100);
  context.fillStyle = "rgba(255,0,0,0.2)";
  context.fillRect(240, 120, 100, 100);
}
create()
</script>
</body>
</html>追问

但是在另外一台电脑上就运行出来了。。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-10-10
打个断点,看卡canvas变量拿到的值是什么!
第2个回答  2016-10-10
额,,看错了。。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网