为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的五角星没有画出来,全黑了呢?

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Document</title>

</head>

<body>

<canvas id="canvas" style="display: block;margin: 0 auto;border: 1px solid #aaa">


</canvas>

<script type="text/javascript">

var searchLight = {x:400,y:300,radius:100,vx:Math.random()*5+10,vy:Math.random()*5+10};

var isIncrease  = true;

window.onload = function(){

canvas.width = 800;

canvas.height = 600;

var context = canvas.getContext("2d");


setInterval(

function(){

draw(context);

update();

},

40

)

}

function draw(cxt){

var canvas = cxt.canvas;

cxt.clearRect(0,0,canvas.width,canvas.height);


cxt.save();

cxt.beginPath();

cxt.fillStyle = "black";

cxt.fillRect(0,0,canvas.width,canvas.height);


cxt.save();

cxt.translate(searchLight.x,searchLight.y);

cxt.scale(searchLight.radius,searchLight.radius);

starPath(cxt);

cxt.fillStyle = "#fff";

cxt.fill();

cxt.restore();

cxt.clip();


cxt.font = "bold 150px Arial";

cxt.textAlign = "center";

cxt.textBaseline = "middle";

cxt.fillStyle = "#058";

cxt.fillText("CANVAS",canvas.width/2,canvas.height/4);

cxt.fillText("CANVAS",canvas.width/2,canvas.height/2);

cxt.fillText("CANVAS",canvas.width/2,canvas.height*3/4);

cxt.restore();

}

function update(){

if(searchLight.radius>700){

isIncrease = false

}else if(searchLight.radius<150){

isIncrease = true;

}

if (isIncrease) {

searchLight += 5;

}else{

searchLight -+ 5;

}

}

//绘制星星

function starPath(cxt){

cxt.beginPath();

for (var i = 0; i < 5; i++) {


cxt.lineTo(Math.cos((18 + i*72)/180*Math.PI),

  -Math.sin((18 + i*72)/180*Math.PI));

cxt.lineTo(Math.cos((54 + i*72)/180*Math.PI)*0.5,

  -Math.sin((54 + i*72)/180*Math.PI)*0.5);

}

cxt.closePath();

}

</script>

</body>

</html>



正在回答

3 回答

我发现你一开始没有定义canvas,然后就直接给canvas设置宽高了

0 回复 有任何疑惑可以回复我~
function update() {

  if (searchLight.radius > 700) {
    isIncrease = false
  } else if (searchLight.radius < 150) {
    isIncrease = true;
  }
  
  /* 修改以下部分即可 */
  ///////////////////////
  if (isIncrease) {
    searchLight.radius += 5;
  } else {
    searchLight.radius -= 5;
  }
  ///////////////////////
}


1 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为什么我的五角星没有画出来,全黑了呢?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信