这篇文章主要介绍了如何使用HTML5中的canvas做恐怖动画,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
效果
万圣节快乐
预备知识
let canvas = document.getElementById('canvas');let context = canvas.getContext('2d');
开始路径
context.beginPath();
beginPath()方法在画布上开始一条绘制路径,或重置当前的路径。
移动路径
context.moveTo();
moveTo()方法把路径移动到画布中指定点,不创建线条。
添加线条
context.lineTo();
lineTo()方法添加一个新点,在画布中创建该点到指定点的线条。
画图drawImage
context.drawImage(image,x,y);
drawImage()方法可以在画布上绘制图像、画布或视频,也可以绘制图像的某些部分,增加/减少图像的尺寸。
获取像素数据
context.getImageData(x,y,width,height);
getImageData()方法可以获取画布imageData对象,该对象指定了矩形的像素数据。
在imageData对象中每个像素都存在rgba值,以数组形式存储在data属性中。
放回像素数据
context.putImageData(imageData,x,y);
putImageData()方法将获取的图像数据放回到画布上。
实现
html
css
html,body,canvas { width: 100%; height: 100%; margin: 0; }.switch {,,,位置:,绝对的,,,,,:,70%,,,,,对的:,10%,,,,,宽度:,50 px;,,,,身高:,50 px;,,,,这个特性:,50 px;,,,,:轮廓,没有,,,,,光标:,指针,,,,,动画:,switch-animate alternate infinite ease 1 s 0; } @keyframes switch-animate {,,,得到{,,,,,,,不必:,0,0,30 px # ece9c5; ,,,},,,,用{,,,,,,,不必:,0,0,100 px # eae5a7; ,,,} }
js
(function (), {,,, class Halloween {,,,,,,,构造函数(id), {,,,,,,,,,,, this.canvas =, . getelementbyid (id),,,,,,,,,,,,, this.ctx =, this.canvas.getContext (& # 39; 2 d # 39;),,,,,,,,,,,,, this.w =, this.canvas.width;,,,,,,,,,,,, this.h =, this.canvas.height;,,,,,,,,,,,, this.data =, []; ,,,,,,,},,,,,,,,//初始画布 ,,,,,,,initDraw (img), {,,,,,,,,,,, this.w =, this.canvas.width =, img.width;,,,,,,,,,,,, this.h =, this.canvas.height =, img.height;,,,,,,,,,,,, this.ctx.drawImage (img, 0, 0),,,,,,,,,,,,, this.data =, this.ctx.getImageData (0, 0, this.w,, this.h); ,,,,,,,},,,,,,,,//显示文字 ,,,,,,,drawText (), {,,,,,,,,,,, this.ctx.font =, & # 39; 60 px verdana # 39;,,,,,,,,,,,,, this.ctx.fillStyle =, & # 39; # ffffff # 39;,,,,,,,,,,,,, this.ctx.fillText(& # 39;万圣节快乐& # 39;,,350,,280); ,,,,,,,},,,,,,,,//闪电 ,,,,,,,闪电(),{,,,,,,,,,,,let ctx =, this.ctx; ,,,,,,,,,,,ctx.strokeStyle =, & # 39; # fff& # 39;; ,,,,,,,,,,,ctx.lineWidth =, 2; ,,,,,,,,,,,ctx.beginPath (); null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null如何使用HTML5中的帆布做恐怖动画