我在繪制地面的時候,線性漸變無法實現,下面是代碼,問題在代碼末尾處,求解
<!DOCTYPE html>
<html>
<head>
?? ?<meta charset="UTF-8">
?? ?<title>繪制一片星空</title>
</head>
<body>
?? ?<canvas id="canvas" style="border:1px black solid;display:block;margin:0 auto;">該瀏覽器不支持canvas配件</canvas>
?? ?<script>
?? ?var canvas=document.getElementById("canvas");
?? ?canvas.width=700;
?? ?canvas.height=500;
?? ?var context=canvas.getContext("2d");
?? ?
?? ?//徑向漸變,設置背景
?? ?setBack(context);
?? ?function setBack(cxt){
?? ??? ?var x=cxt.createRadialGradient(351,500,0,350,500,500);
?? ??? ?x.addColorStop(0.0,"#035")
?? ??? ?x.addColorStop(1.0,"black");
?? ??? ?context.fillStyle=x;
?? ??? ?context.fillRect(0,0,700,500);
?? ?}
?? ?//繪制星星
?? ?addStar(context);
?? ?function addStar(cxt){
?? ??? ?for(var i=0;i<100;i++){
?? ??? ??? ?var x=Math.random()*700;
?? ??? ??? ?var y=Math.random()*300;
?? ??? ??? ?var deg=Math.random()*Math.PI*2;
?? ??? ??? ?// var sx=Math.random()*2;
?? ??? ??? ?// var sy=Math.random()*2;
?? ??? ??? ?cxt.save();
?? ??? ??? ?cxt.translate(x,y);
?? ??? ??? ?cxt.rotate(deg);
?? ??? ??? ?//cxt.scale(sx,sy);//沒有必要的縮放,效果也不對,并沒有縮放大小,不是預想中的效果
?? ??? ??? ?drawStar(cxt);
?? ??? ??? ?
?? ??? ??? ?cxt.stroke();
?? ??? ??? ?cxt.fillStyle="yellow";
?? ??? ??? ?cxt.fill();
?? ??? ??? ?cxt.restore();
?? ??? ?}
?? ?}
?? ?// drawStar(context);
?? ?function drawStar(cxt){
?? ??? ?var R=10;
?? ??? ?var r=5;
?? ??? ?var deg=18;
?? ??? ?cxt.beginPath();
?? ??? ?for(var i=0;i<5;i++){
?? ??? ??? ?cxt.lineTo(R*Math.cos((deg+i*72)/360*2*Math.PI),-R*Math.sin((deg+i*72)/360*2*Math.PI));
?? ??? ??? ?cxt.lineTo(r*Math.cos((deg+36+i*72)/360*2*Math.PI),-r*Math.sin((deg+36+i*72)/360*2*Math.PI));
?? ??? ?}
?? ??? ?cxt.closePath();
?? ?}
?? ?//繪制月亮
?? ?drawMoon(context);
?? ?function drawMoon(cxt){
?? ??? ?cxt.save();
?? ??? ?cxt.translate(500,150);
?? ??? ?cxt.rotate(Math.PI/6);
?? ??? ?cxt.beginPath();
?? ??? ?cxt.arc(0,0,100,Math.PI*0.5,Math.PI*1.5,true);
?? ??? ?cxt.moveTo(0,-100);
?? ??? ?cxt.quadraticCurveTo(80,0,0,100);
?? ??? ?cxt.closePath();
?? ??? ?cxt.fillStyle="yellow";
?? ??? ?cxt.fill();
?? ??? ?cxt.restore();
?? ?}
?? ?//繪制彎曲的地面
?? ?drawGround(context);
?? ?function drawGround(cxt){
?? ??? ?cxt.save();
?? ??? ?cxt.beginPath();
?? ??? ?cxt.moveTo(0,350);
?? ??? ?cxt.bezierCurveTo(340,300,350,500,700,350);
?? ??? ?cxt.lineTo(700,500);
?? ??? ?cxt.lineTo(0,500);
?? ??? ?cxt.closePath();
?? ??? ?//繪制地面時出現問題
?? ??? ?var landstyle=cxt.createLinearGradient(0,500,0,0);
?? ??? ?landstyle.addColorStop=(0.0,'#030');
?? ??? ?landstyle.addColorStop=(1.0,'#580');
?? ??? ?cxt.fillStyle=landstyle;
?? ??? ?cxt.fill();
?? ??? ?cxt.restore();
?? ?}
?? ?</script>
</body>
</html>
2016-12-01
兄弟啊。。。addColorStop不是屬性 是方法?
landstyle.addColorStop(0,'#030');
landstyle.addColorStop(1,'#580');
這樣就可以了
2017-05-03
哦哦,我知道了
2017-05-03
為什么我這樣寫沒有漸變呢
landStyle.addColorStop(0.0,"#030");
landStyle.addColorStop(1.0,"#000");