Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Canvas绘画常用方法

先说一下canvas元素比较游泳的方法主要是canvas通过getContext()方法获取的上下文对象。其次设置颜色方面,通常有四种方法:16进制颜色值、英语单词、rgb、rgba。主要注意的是后两者,rgb的三个参数是红绿蓝0-255的值,rgba在此基础上添加了第四个参数透明度,范围0-1。1.画矩形 <!DOCTYPE html><html><head lang="en"><meta charset="utf-8"><title></title><script>//画矩形function drawRect(id){var canvas = document.getElementById(id); //获取上下文对象,canvas很多常用方法都是基于这个对象实现的var context = canvas.getContext("2d");//目前参数只有2dcontext.fillStyle = "gray"; //填充颜色context.strokeStyle = "#f60"; //边框颜色context.lineWidth = 5;//边框宽度context.fillRect(0,0,400,300); //参数:x,y,width,height。绘制“已填色”的矩形,默认填充颜色是黑色context.strokeRect(80,80,180,120); //参数:x,y,width,height。绘制未填色的矩形,默认填充颜色是黑色context.strokeRect(110,110,180,120);}</script><head><body onload="drawRect("canvas");"><canvas id="canvas" width="400px" height="400px" ></canvas></body></html>JavaScript已经是所有浏览器的默认脚本语言,因此<script>标签中无需再指定脚本类型。2.画圆<!DOCTYPE html><html><head lang="en"><meta charset="utf-8"><title></title><script>//画圆形function drawArc(id){var canvas = document.getElementById(id); //获取上下文对象,canvas很多常用方法都是基于这个对象实现的var context = canvas.getContext("2d");//目前参数只有2dcontext.fillStyle = "#f1f2f3";//填充颜色context.fillRect(0,0,400,400);//参数:x,y,width,height。绘制“已填色”的矩形,默认填充颜色是黑色for(var i=1; i<10; i++){context.beginPath();//路径开始i % 2 ? context.arc(200,200,10*i,0,Math.PI,true): context.arc(200,200,10*i,0,Math.PI,false); //参数:x,y,半径,开始角度,结束角度,是否按顺时针方向context.closePath();//路径关闭context.fillStyle = "rgba(255,0,0,0.25)"; //填充颜色context.fill(); //绘制}}</script><head><body onload="drawArc("canvas");"><canvas id="canvas" width="400px" height="400px" ></canvas></body></html>3.写字 <!DOCTYPE html><html><head lang="en"><meta charset="utf-8"><title></title><script>//写字function drawText(id){var canvas = document.getElementById(id); //获取上下文对象,canvas很多常用方法都是基于这个对象实现的var context = canvas.getContext("2d");//目前参数只有2dcontext.fillStyle = "gray"; //填充颜色context.fillRect(0,0,800,300);//参数:x,y,width,height。绘制“已填色”的矩形,默认填充颜色是黑色context.fillStyle = "#fff"; //填充颜色context.strokeStyle = "#fff"; //边框颜色context.font = "bold 40px "微软雅黑"";//设置字体//context.textBaseline = "Top"; context.textAlign = "start"; 文字相对于浏览器顶部和左侧的对齐方式context.fillText("Canvas",50,50);context.strokeText("Canvas",70,100);}</script><head><body onload="drawText("canvas");"><canvas id="canvas" width="400px" height="400px" ></canvas></body></html> textBaseline和textAlign特点可以查看其他资源,就不在这混乱主题了。 4.将画保存window.location = canvas.toDataURL("image/jpeg"); //保存图像可以选择自己想要的格式。5.动画var i=100;function painting(){//alert(1);context.fillStyle = "gray"; //填充颜色context.fillRect(i,0,10,10);//参数:x,y,width,height。绘制“已填色”的矩形,默认填充颜色是黑色i=i+20;}function draw(id){var canvas = document.getElementById(id); //获取上下文对象,canvas很多常用方法都是基于这个对象实现的var context = canvas.getContext("2d");//目前参数只有2dsetInterval(painting,100);//事件单位是毫秒i=0;}这个没有做出效果。看到别人用上面的方法,但是我这样写没有出来动画,调试果然显示painting函数内的context为定义。以后有时间再学习一下。本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-01/127512.htm