const ctx = canvas.getContext(“2d”); //准备画笔
//画矩形// ctx.rect(x,y,w,h)
ctx.rect(50, 50, 80, 80)
// ctx.stroke();
//画弧形 原型 ctx.arc(x,y,r,star,end)
ctx.arc(40,40,30,0,Math.PI*2)
ctx.stroke();
画空心 stroke()
画实心 fill()
画笔样式
画笔颜色:空心颜色strokestyle 实心颜色fillstyle
画笔粗细:lineWidth=20
ctx.lineWidth=20;
ctx.strokeStyle='red';
ctx.fillStyle='pink'
雨滴案例
window.addEventListener(“load”, () => {
//1.准备画布
const canvas = document.querySelector(“canvas”);
//1.1设置画布大小
const tools = {
random(min, max) {
return Math.random() * (max - min) + min
}
}
//准备雨滴数组,用来循坏
let rainArr = []
let w, h;
let size = function () {
w = window.innerWidth;
h = window.innerHeight;
canvas.width = w;
canvas.height = h;
// canvas.style.background = ‘pink’;
}
size();
//2.准备画笔
const ctx = canvas.getContext(“2d”);
window.addEventListener(‘resize’, size)
//3。想象 4.绘制
//3用构造函数方法构建雨滴效果
//3.1 雨滴创建并落下
//3.3.1创建雨滴构造函数
class Rain {
constructor() {
}
init(){
this.x = tools.random(0, w);
this.y = 0;
this.w = tools.random(3, 5);
this.h = tools.random(15, 25);
//雨滴颜色
this.color = 'blue'
this.vy = tools.random(3,5)//雨滴速度
this.g = 0.1;//重力
//雨滴落地的位置
this.floor=tools.random(50,100)
//水花基本数据
this.r=0;
this.maxR=50;
this.drawRain();
}
//3.1.3根据雨滴数据创建雨滴
drawRain() {
ctx.beginPath()
ctx.rect(this.x, this.y, this.w, this.h);
ctx.fillStyle = this.color;
ctx.fill();
}
drawFlower(){
ctx.beginPath();
ctx.arc(this.x+this.w/2,this.y+this.h,this.r,0,Math.PI*2)
ctx.strokeStyle=this.color
ctx.stroke();
}
//3.1.4让雨滴落下 改变雨滴基本数据
rainDown() {
//改变Y轴数据
this.vy += this.g;
this.y += this.vy;//运动规则
if(this.y>=h-this.floor){
this.y=h-this.floor;
this.r++;
if(this.r>this.maxR){
this.init();
}
this.drawFlower()
}else{
this.drawRain()
}
}
}
//创建雨滴实例
//需要多个雨滴,用循坏
function raining(number) {
for (var i = 0; i < number; i++) {
setTimeout(() => {
let rain = new Rain();
rain.init()
//把雨滴收集的数组 依次添加到rainArr中
rainArr.push(rain);
rain.drawRain();
}, 100 * i)
}
setInterval(() => {
//把收集来的雨滴全部下落
for (let item of rainArr) {
item.rainDown()
}
//加蒙版让雨滴效果变浅,有个下落的过程
ctx.beginPath()
ctx.rect(0,0,w,h)
// ctx.fillStyle='rgba(255,255,255,0.1)'
ctx.fillStyle='rgba(0,0,0,0.1)'
ctx.fill()
},1000/60)
}
raining(50);
})