赞
踩
- </pre><pre name="code" class="html"><!doctype html>
- <html>
- <head></head>
- <body>
- <canvas width="800" height="800" style="background:#888" id="canvas">
- 您的浏览器当前版本不支持canvas标签
- </canvas>
- <script>
- //获取画布DOM 还不可以操作
- var canvas=document.getElementById('canvas');
-
- //设置绘图环境
- var cxt=canvas.getContext('2d');
-
-
- //画一条线段。
- cxt.beginPath(); //开启新路径
- cxt.lineWidth=10; //设定画笔的宽度
- cxt.strokeStyle="red"; //设置画笔的颜色
- cxt.moveTo(20,20); //设定笔触的位置
- cxt.lineTo(100,20); //设置移动的方式
- cxt.stroke(); //画线
- cxt.closePath(); //封闭路径
-
-
- //画一个空心圆形 凡是路径图形必须先开始路径,画完图之后必须结束路径
- cxt.beginPath();
- cxt.lineWidth=3; //重新设置画笔
- cxt.strokeStyle="green";
- cxt.arc(200,200,50,0,360,false);
- cxt.stroke();
- cxt.closePath();
-
- //画一个实心圆形
- cxt.beginPath();
- cxt.fillStyle="rgb(255,0,0)"; //设置填充的颜色
- cxt.arc(200,100,50,0,360,false);
- cxt.fill();
- cxt.stroke();
- cxt.closePath();
-
- //画一个矩形
- cxt.beginPath();
- cxt.rect(300,20,100,100);
- cxt.stroke();
- cxt.closePath();
- cxt.strokeRect(300,150,100,100); //其他方法 建议使用此方式
-
- //实心矩形
- cxt.beginPath();
- cxt.rect(300,270,100,100);
- cxt.fill();
- cxt.closePath();
- cxt.fillRect(300,390,100,100);
-
- //设置文字
- cxt.font="40px 宋体"; //css font属性
- cxt.fillText("canvas",20,300);
- cxt.lineWidth=1; //将笔触设置为1像素
- cxt.strokeText("canvas",20,350);
-
- //画图 把一幅图片画到画布中 注意webkit内核的浏览器 chrome和猎豹不支持
- var img =new Image();
- img.src="xiaomm.jpg";
- cxt.drawImage(img,20,370,230,306);
-
- //画一个三角形
- cxt.beginPath();
- cxt.moveTo(300,500); //移动至开始点
- cxt.lineTo(300,600);
- cxt.lineTo(400,550);
- cxt.closePath();//填充或者画路径需要先闭合路径再画
- cxt.stroke();
-
- //实心
- cxt.beginPath();
- cxt.moveTo(300,600); //移动至开始点
- cxt.lineTo(300,700);
- cxt.lineTo(400,650);
- cxt.closePath();
- cxt.fill();
-
- //旋转条形
- //设置旋转环境
- cxt.save();
- cxt.translate(10,10); //在异次元空间重置0,0点的位置
- cxt.rotate(-350*Math.PI/180); //设置旋转角度 参数是弧度 角度 0-360 弧度=角度*Math.PI/180
- cxt.lineWidth=10; //旋转一个线段
- cxt.beginPath();
- cxt.moveTo(0,0);
- cxt.lineTo(20,100);
- cxt.stroke();
- cxt.closePath();
- //将旋转之后的元素放回原画布
- cxt.restore();
-
- //旋转图片
- cxt.save();
- cxt.translate(20,370);
- cxt.rotate(-50*Math.PI/180);
-
- var img = new Image();
- img.src="ccc.jpg";
- cxt.drawImage(img,0,0,230,306);
- cxt.restore();
-
-
- //上面代码会产生一个小圆点,每隔30毫秒就向右下方移动的效果。setInterval函数的一开始,之所以要将画布重新渲染黑色底色,是为了抹去上一步的小圆点先上升后下降
- /*
- var posX = 20,
- posY = 100;
- setInterval(function() {
- cxt.fillStyle = "black";
- cxt.fillRect(0,0,canvas.width, canvas.height);
- posX += 1;
- posY += 0.25;
- cxt.beginPath();
- cxt.fillStyle = "white";
- cxt.arc(posX, posY, 10, 0, Math.PI*2, true);
- cxt.closePath();
- cxt.fill();
- }, 30);
- */
-
- </script>
-
-
-
- </body>
- </html>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。