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

来源:8-3 clip和剪辑区域

王光

2017-12-21 10:10

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

  • 慕移动9181930
    2022-03-24 01:11:46
  • qq_夏天的回忆_0
    2018-11-02 10:29:42

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

  • Tom_Kwok
    2017-12-22 01:32:33
    function update() {
    
      if (searchLight.radius > 700) {
        isIncrease = false
      } else if (searchLight.radius < 150) {
        isIncrease = true;
      }
      
      /* 修改以下部分即可 */
      ///////////////////////
      if (isIncrease) {
        searchLight.radius += 5;
      } else {
        searchLight.radius -= 5;
      }
      ///////////////////////
    }


Canvas绘图详解

Canvas系列教程第二课,详解Canvas各接口,让同学彻底掌握Canvas绘图

72881 学习 · 422 问题

查看课程

相似问题