[英]Is there a good method for dynamically drawing clouds with HTML5 canvas and javascript without using images?
I am trying to create a background for my website that uses canvases to draw stuff, get the data URL of it and set it as the background-image property of an element. 我正在尝试为我的网站创建一个背景,使用画布绘制东西,获取它的数据URL并将其设置为元素的background-image属性。 The method works, but I can't find a good way to draw a cloud on the canvas.
该方法有效,但我找不到在画布上绘制云的好方法。 Other simpler things like the sun and stars are easy to do without images, and I would prefer to keep the entire script image-less.
其他更简单的东西,如太阳和星星,很容易做到没有图像,我宁愿保持整个脚本没有图像。 Drawing a multitude of circles around a point can slightly do it, but I would prefer a more realistic way to do it.
在一个点周围绘制多个圆圈可以稍微做一些,但我更愿意采用更现实的方式来做到这一点。 Thanks in advance.
提前致谢。
I have just created Cloudgen.js, an open source library that generates clouds for the canvas. 我刚刚创建了Cloudgen.js,一个为画布生成云的开源库。 The approach I took uses overlapping circles, each with a radial gradient and transparency.
我采用的方法使用重叠圆,每个圆都有径向渐变和透明度。 Cloudgen.js provides a way to draw a single cloud with the "drawCloud" method or many clouds at once with "drawCloudGroup".
Cloudgen.js提供了一种使用“drawCloud”方法绘制单个云的方法,或使用“drawCloudGroup”一次绘制多个云。 As clouds are roughly circular, using "drawCloudGroup" also allows you to create single clouds with more interesting or predefined shapes.
由于云大致呈圆形,因此使用“drawCloudGroup”还可以创建具有更多有趣或预定义形状的单个云。
You can find Cloudgen.js at https://github.com/Ninjakannon/Cloudgen.js 您可以在https://github.com/Ninjakannon/Cloudgen.js找到Cloudgen.js
Ok, I have been thinking about the problem of draw clouds, and this is where I am at. 好吧,我一直在考虑绘制云的问题,这就是我所处的位置。
HTMLCanvasElement.prototype.makeCloud=function (xLast, yLast, rLast, lLast){
rLast = (rLast || 50)
lLast = lLast || Math.random()*25+75;
var x = (xLast || 250) + Math.random()*(2*rLast)-rLast/1,
y = (yLast || 250) + Math.random()*(1*rLast)-rLast/1.5,
r = (rLast) + Math.random()*10-7.5,
l = (lLast);
if(x-r < 0)
x = r+1;
else if (x+r > this.width)
x = this.width-r-1;
if(y-r < 0)
y = r+1;
else if (y+r > this.height)
y = this.height-r-1;
if(r <= 0)
return this;
if(l<0)
l=0;
else if(l>100)
l=100;
var ctx=this.getContext('2d');
ctx.fillStyle='hsl(0, 0%, '+l+'%)';
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
if(Math.random < 0.01)
return this;
this.makeCloud(x, y, r, l)
return this;
}
It generates some pretty crazy stuff... can anyone think of any improvements? 它会产生一些非常疯狂的东西......任何人都可以想到任何改进吗? i know editing the canvas prototype isn't the best thing to do, but my application uses a bit of chaining and this makes it flow better.
我知道编辑canvas原型并不是最好的事情,但我的应用程序使用了一些链接,这使它更好地流动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.