代码实现说明 1.创建画布与图片 - // 创建画布
- var ctx = canvas.getContext('2d');
- // 创建图片对象
- var heartImage = new Image();
复制代码2.创建爱心对象 type参数为0就显示随机文字,否则只显示爱心不显示文字 - 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.通过爱心绘制方法在画布上绘制爱心图片的位置 - 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();
- }
复制代码- // 爱心变动
- Heart.prototype.update = function()
复制代码4.使用定时器实时绘制爱心 - function render(){
- ctx.clearRect(0, 0, wW, wH);
- for(var i = 0; i < hearts.length; i++){
- hearts[i].draw();
- hearts[i].update();
- }
- requestAnimationFrame(render);
- }
复制代码
|