web前端|H5教程
Canvas,draw,动画
web前端-H5教程
HTML5 Canvas动画效果演示
主要思想:
首先要准备一张有连续帧的图片,然后利用HTML5 Canvas的draw方法在不同的时间间隔绘制不同的帧,这样看起来就像动画在播放。
关键技术点:
JavaScript 函数setTimeout()有两个参数,第一个是参数可以传递一个JavaScript方法,
另外一个参数代表间隔时间,单位为毫秒数。代码示例:
setTimeout( update, 1000/30);
Canvas的API-drawImage()方法,需要指定全部9个参数:
ctx.drawImage(myImage, offw, offh, width,height, x2, y2, width, height);
其中offw, offh是指源图像的起始坐标点,width, height表示源图像的宽与高,x2,y2表
示源图像在目标Canvas上的起始坐标点。
一个22帧的大雁飞行图片实现的效果:
拦截码源码吧,vscode编辑unity,Ubuntu密钥环设置,tomcat 关掉 日志,sqlite开源协议,bootstrap step 插件,python用什么前端框架,爬虫 优酷,php 数组 多维,seo 锚文本,电视直播 手机版 网站源码,网页内搜索代码,dz论坛模板家具,webapp页面源代码,网站管理系统制作,新云4.0建站程序源码下载lzw
源图像:
15源码,vscode快速定位行,ubuntu 证书管理,tomcat的conf文件,sqlite3 字段名称,美篇里的数据可以爬虫爬取么,php json 实例,烟台seo排名优化,html5微信网站模板,织梦dedecms后台模板utf-8lzw
程序代码:
电动车网站 源码,vscode提示语言修改中文,ubuntu教程视频,ios tomcat,sqlite 详解,家电网页设计,php连接数据库的方法,什么是1u服务器,微擎插件源码怎么安装,前端模板和前端框架,爬虫股民,php配置文件在哪,个人seo外包,springboot卡住了,织梦导航下拉菜单标签,网站制作教程pdf,手机网页加载更多,淘宝客模板.rar,sitefactory后台,h5登陆页面代码,管理系统 wpf,wap手机网站程序lzw
复制代码代码如下:
var ctx = null; // global variable 2d context
var started = false;
var mText_canvas = null;
var x = 0, y =0;
var frame = 0; // 22 5*5 + 2
var imageReady = false;
var myImage = null;
var px = 300;
var py = 300;
var x2 = 300;
var y2 = 0;
window.onload = function() {
var canvas = document.getElementById(“animation_canvas”);
console.log(canvas.parentNode.clientWidth);
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
if (!canvas.getContext) {
console.log(“Canvas not supported. Please install a HTML5 compatible browser.”);
return;
}
// get 2D context of canvas and draw rectangel
ctx = canvas.getContext(“2d”);
ctx.fillStyle=”black”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
myImage = document.createElement(‘img’);
myImage.src = “../robin.jpg”;
myImage.onload = loaded();
}
function loaded() {
imageReady = true;
setTimeout( update, 1000/30);
}
function redraw() {
ctx.clearRect(0, 0, 460, 460)
ctx.fillStyle=”black”;
ctx.fillRect(0, 0, 460, 460);
// find the index of frames in image
var height = myImage.naturalHeight/5;
var width = myImage.naturalWidth/5;
var row = Math.floor(frame / 5);
var col = frame – row * 5;
var offw = col * width;
var offh = row * height;
// first robin
px = px – 5;
py = py – 5;
if(px < -50) {
px = 300;
}
if(py < -50) {
py = 300;
}
//var rate = (frame+1) /22;
//var rw = Math.floor(rate * width);
//var rh = Math.floor(rate * height);
ctx.drawImage(myImage, offw, offh, width, height, px, py, width, height);
// second robin
x2 = x2 – 5;
y2 = y2 + 5;
if(x2 < -50) {
x2 = 300;
y2 = 0;
}
ctx.drawImage(myImage, offw, offh, width, height, x2, y2, width, height);
}
function update() {
redraw();
frame++;
if (frame >= 22) frame = 0;
setTimeout( update, 1000/30);
}
HTML Canvas Animations Demo – By Gloomy Fish
Play Animations
发现上传透明PNG格式有点问题,所以我上传不透明的图片。可以用其它图片替换,替换以后请修改最大帧数从22到你的实际帧数即可运行。