淡漠2
2016-08-04 17:05
<canvas id="star" style="border:1px solid #aaa;display:block;margin:50px auto;"></canvas>
//一片星空
function starTwo() {
var canvas = document.getElementById("star");
canvas.width = 1200;
canvas.height = 800;
var context = canvas.getContext("2d");
var skyStyle = context.createLinearGradient(0, 0, 0, canvas.height);
skyStyle.addColorStop(0.0, "#000");
skyStyle.addColorStop(1.0, "#035");
context.fillStyle = skyStyle;
context.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < 200; i++) {
var r = Math.random() * 5 + 5;
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height*0.65;
var a = Math.random() * 360;
drawStarTwo(context, x, y, r, a);
}
}
//绘制五角星
function drawStarTwo(cxt, x, y, R, rot) {
cxt.save();
cxt.rotate(rot / 180 * Math.PI);
cxt.translate(x, y);
//cxt.scale(R, R);
starPath(cxt);
cxt.fillStyle = "#fb3";
cxt.fill();
cxt.restore();
//绘制出在(x,y),大小为R,旋转rot度的五角星
}
function starPath(cxt) {
cxt.beginPath();
for (var i = 0; i < 5; i++) {
cxt.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI)*20 , -Math.sin((18 + i * 72 ) / 180 * Math.PI)*20);
cxt.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * 0.5*20, -Math.sin((54 + i * 72 ) / 180 * Math.PI) *0.5*20);
}
cxt.closePath();
}
window.onload = function () {
starTwo();
}
在drawStarTwo函数中,把cxt.translate(x, y)放在cxt.rotate(rot / 180 * Math.PI);之前,就可以了。
怎么会变少?i=0;i<200,画200次星星。 是因为画布变宽了,星星分布稀疏,看起来少了吧
Canvas绘图详解
72881 学习 · 422 问题
相似问题