1.创建画布与图片
1 2 3 4  | // 创建画布var ctx = canvas.getContext('2d');// 创建图片对象var heartImage = new Image(); | 
2.创建爱心对象
type参数为0就显示随机文字,否则只显示爱心不显示文字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32  | function Heart(type){    this.type = type;    // 初始化生成范围    this.x = Math.random() * wW;    this.y = Math.random() * wH;    this.opacity = Math.random() * .5 + .5;    // 偏移量    this.vel = {        x: (Math.random() - .5) * 5,        y: (Math.random() - .5) * 5    }    this.initialW = wW * .5;    this.initialH = wH * .5;    // 缩放比例    this.targetScale = Math.random() * .15 + .02; // 最小0.02    this.scale = Math.random() * this.targetScale;    // 文字位置    this.fx = Math.random() * wW;    this.fy = Math.random() * wH;    this.fs = Math.random() * 10;    this.text = getText();    this.fvel = {        x: (Math.random() - .5) * 5,        y: (Math.random() - .5) * 5,        f: (Math.random() - .5) * 2    }} | 
3.通过爱心绘制方法在画布上绘制爱心图片的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14  | Heart.prototype.draw = function(){    ctx.save();    ctx.globalAlpha = this.opacity;    ctx.drawImage(heartImage, this.x, this.y, this.width, this.height);    ctx.scale(this.scale + 1, this.scale + 1);        if(!this.type){            // 设置文字属性        ctx.fillStyle = getColor();            ctx.font = 'italic ' + this.fs + 'px sans-serif';            // 填充字符串            ctx.fillText(this.text, this.fx, this.fy);        }    ctx.restore();} | 
1 2  | // 爱心变动Heart.prototype.update = function() | 
4.使用定时器实时绘制爱心
1 2 3 4 5 6 7 8  | function render(){    ctx.clearRect(0, 0, wW, wH);    for(var i = 0; i < hearts.length; i++){        hearts[i].draw();        hearts[i].update();    }    requestAnimationFrame(render);} | 
特别申明:
			本站所有资源都是由网友投稿发布,或转载各大下载站,请自行检测软件的完整性!
			本站所有资源仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您自己承担!
			如有侵权请联系我们删除下架,联系方式:lei1294551502@163.com