Home  >  Article  >  Web Front-end  >  Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

不言
不言forward
2018-12-31 09:33:503557browse

This article brings you an introduction to the implementation methods of ordinary motion effects and particle motion effects in canvas (code examples). It has certain reference value and friends in need can refer to it. I hope it helps you.

Canvas is used to draw images and animations on web pages. It can be understood as a canvas, and the desired effect is built on this canvas.

Canvas can draw dynamic effects. In addition to commonly used regular animations, the concept of particles can also be used to achieve more complex dynamic effects. This article uses ordinary dynamic effects and particle special effects to implement a simple clock.

Ordinary clock

Ordinary animation uses the canvas API to achieve regular patterns and animations.

Effect

Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

This effect is relatively simple to achieve. It mainly analyzes the angle offset between the scale and the pointer. accomplish.

Drawing scale

This example is the drawing of hour scale: there are 12 hours on the dial, Math.PI is 180°, and each hour occupies 30°.
.save() means to save the state of the current canvas environment and draw on this basis. After drawing is completed, the previously saved path status and attributes are returned.

The minute scale is the same, just change the angle and style.

  // 小时时间刻度
  offscreenCanvasCtx.save();
  for (var i = 0; i <p><strong>The pointer points to</strong></p><p>Take the second hand as an example: get the seconds of the current time and calculate the corresponding offset angle</p><pre class="brush:php;toolbar:false">  var now = new Date(),
    sec = now.getSeconds(),
    min = now.getMinutes(),
    hr = now.getHours();
  hr = hr > 12 ? hr - 12 : hr;
  //秒针
  offscreenCanvasCtx.save();
  offscreenCanvasCtx.rotate(sec * (Math.PI / 30));
  ......
  offscreenCanvasCtx.stroke();

Particle animation

canvas can be used to draw complex, irregular animations. Particle effects can be used to achieve complex, random dynamic effects.

Particles refer to each pixel in the image data imageData. After obtaining each pixel, add attributes or events to interact with the particles in the area to achieve dynamic effects.

Effect

Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

Particle Acquisition

The following image conversion is an example. The effect is first applied to canvas Render the image and then obtain each pixel of the area where the text is located.

  let image = new Image();
  image.src='../image/logo.png';
  let pixels=[]; //存储像素数据
  let imageData;
  image.width = 300;
  image.height = 300
  // 渲染图片,并获取该区域内像素信息
  image.onload=function(){
    ctx.drawImage(image,(canvas.width-image.width)/2,(canvas.height-image.height)/2,image.width,image.height);
    imageData=ctx.getImageData((canvas.width-image.width)/2,(canvas.height-image.height)/2,image.width,image.height); //获取图表像素信息
 //绘制图像
  };

Pixel information

The size of the picture is 300*300, with a total of 90,000 pixels. Each pixel occupies 4 bits and stores rgba data.

Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

Particle Drawing

  function getPixels(){
    var pos=0;
    var data=imageData.data; //RGBA的一维数组数据
    //源图像的高度和宽度为300px
    for(var i=1;i=0){
          var pixel={
            x:(canvas.width-image.width)/2+j+Math.random()*20, //重新设置每个像素的位置信息
            y:(canvas.height-image.height)/2+i+Math.random()*20, //重新设置每个像素的位置信息
            fillStyle:'rgba('+data[pos]+','+(data[pos+1])+','+(data[pos+2])+','+(data[pos+3])+')'
          }
          pixels.push(pixel);
        }
      }
    }
  }
  function drawPixels() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.clearRect(0,0,canvas.width,canvas.height);
    var len = pixels.length, curr_pixel = null;
    for (var i = 0; i <h1>Particle Clock</h1><h2>Rendering Text Clock</h2><pre class="brush:php;toolbar:false">  function time() {
    ctx.clearRect(0,0,canvas.width,canvas.height)
    ctx.font = "150px 黑体";
    ctx.textBaseline='top';
    ctx.fillStyle = "rgba(245,245,245,0.2)";
    ctx.fillText(new Date().format('hh:mm:ss'),(canvas.width-textWidth)/2,(canvas.height-textHeight)/2,textWidth,textHeight);
  }

Effect

Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

获取粒子

文字转换粒子概念同上,获取选定区域的像素,根据筛选条件进行选择并存入数组。经过遍历后重新绘制。

  function getPixels(){
    let imgData = ctx.getImageData((canvas.width-textWidth)/2,(canvas.height-textHeight)/2,textWidth,textHeight);
    let data = imgData.data
    pixelsArr = []
    for(let i=1;i=0){
          var pixel={
            x:j+Math.random()*20, //重新设置每个像素的位置信息
            y:i+Math.random()*20, //重新设置每个像素的位置信息
            fillStyle:'rgba('+data[pos]+','+(data[pos+1])+','+(data[pos+2])+','+(data[pos+3])+')'
          };
          pixelsArr.push(pixel);
        }
      }
    }
  }

imgData保存了所选区域内的像素信息,每个像素点占据4位,保存了RGBA四位信息。筛选每个像素的第四位,这段代码中将所有透明度不为0的像素都保存到了数组pixelsArr中。

xy记载了该粒子的位置信息,为了产生效果图中的运动效果,给每个粒子添加了0-20个像素的偏移位置,每次重绘时,偏移位置随机生成,产生运动效果。

粒子重绘

获取粒子之后,需要清除画布中原有的文字,将获取到的粒子重新绘制到画布上去。

  function drawPixels() {
    // 清除画布内容,进行重绘
    ctx.clearRect(0,0,canvas.width,canvas.height);
    for (let i in pixelsArr) {
      ctx.fillStyle = pixelsArr[i].fillStyle;
      let r = Math.random()*4
      ctx.fillRect(pixelsArr[i].x, pixelsArr[i].y, r, r);
    }
  }

粒子重绘时的样式为筛选像素时原本的颜色与透明度,并且每个在画布上绘制每个粒子时,定义大小参数r,r取值为0-4中随机的数字。最终生成的粒子大小随机。

实时刷新

获取粒子并成功重绘之后,需要页面实时刷新时间。这里采用window.requestAnimationFrame(callback)方法。

  function time() {
    ......
    getpixels(); //获取粒子
    drawPixels(); // 重绘粒子
    requestAnimationFrame(time);
  }

window.requestAnimationFrame(callback) 方法告诉浏览器您希望执行动画并请求浏览器在下一次重绘之前调用指定的函数来更新动画。该方法使用一个回调函数作为参数,这个回调函数会在浏览器重绘之前调用。

该方法不需要设置时间间隔,调用频率采用系统时间间隔(1s)。

文档解释戳这里

效果


Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example)

总结

本文主要通过两种不同的方式实现了时钟的动态效果,其中粒子时钟具有更多的可操作性。在以后的canvas系列中会针对粒子系统实现更多的动态效果。




The above is the detailed content of Implementation of ordinary motion effects and particle motion effects in canvas Method introduction (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete