本文介绍了线段、圆、矩形、字体、多边形、图像的绘制以及图形的旋转。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="canvas" width="1000" height="900" style="background: #F7F7F7">
您的浏览器不支持canvas属性
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d'); //设置绘制环境
//1、画一条线段
ctx.beginPath(); //开始,开始路径,凡是路径图形必须先开始路径,画完结束路径
ctx.lineWidth = 5; //设置画笔的宽度
ctx.strokeStyle = "#00ff00"; //设置画笔的颜色
ctx.moveTo(10 , 10); //设置线条开始坐标
ctx.lineTo(200 , 30); //设置线条结束坐标
ctx.stroke(); //绘制线条
ctx.closePath(); //画完,封闭路径
//2、画一个空心圆
ctx.beginPath(); //开始,开始路径
//重新设置画笔,若不重新设置,则使用最近一次的设置
ctx.lineWidth = 3; //设置画笔的宽度
ctx.strokeStyle = "yellow"; //设置画笔的颜色
ctx.arc(100 , 100 , 20 , 0 , 360); //arc(x,y,r,start,stop)
ctx.stroke();
ctx.closePath(); //画完,封闭路径
//3、画一个实心圆
ctx.beginPath(); //开始,开始路径
ctx.fillStyle = "rgb(255 , 0 , 0)"; //设置填充颜色
ctx.arc(200 , 100 , 20 , 0 , 360);
ctx.fill(); //填充内部
ctx.stroke(); //画边线
ctx.closePath(); //画完,封闭路径
//4、画空心矩形,非路径图形,不用开始和结束路径,但是建议加上
//1)、方法一:
ctx.beginPath();
ctx.rect(10 , 150 , 50 , 30); //(x , y , width , height)
ctx.stroke();
ctx.closePath();
//2)、方法二:(建议用这种)
ctx.strokeRect(100 , 150 , 50 , 30); //(x , y , width , height)
//5、画实心矩形
//1)、方法一:
ctx.beginPath();
ctx.rect(200 , 150 , 50 , 30);
ctx.fill();
ctx.closePath();
//2)、方法二:(建议用这种)
ctx.fillRect(300 , 150 , 50 , 30);
//6、画实心字
ctx.font = "40px 黑体";
ctx.fillText("学习HTML5" , 10 , 250); ////(text , x , y)
//7、画空心字
ctx.font = "50px 微软雅黑";
ctx.strokeStyle = "green";
ctx.lineWidth = 1;
ctx.strokeText("学习HTML5" , 250 , 250);
//8、画图,把一张图片画到画布中,webkit内核的浏览器chrome和猎豹不支持
var img = new Image();
img.src = "beauty.jpg";
ctx.drawImage(img , 10 , 280 , 540 , 360);//drawImage(img , x , y , imgWidth , imgHeight)
//9、画空心三角形
ctx.beginPath();
ctx.moveTo(650 , 10);
ctx.lineTo(650 , 50);
ctx.lineTo(750,50);
ctx.closePath(); //填充或画路径需先关闭路径再画
ctx.stroke();
//10、画实心三角形
ctx.beginPath();
ctx.moveTo(800 , 10);
ctx.lineTo(800 , 50);
ctx.lineTo(900,50);
ctx.closePath();
ctx.fill();
//11、旋转
ctx.save(); //设置旋转环境
ctx.translate(10 ,10); //在异次元空间重置00点的位置,默认为画布的起点
ctx.rotate(30 * Math.PI / 180); //设置旋转角度
//旋转1中的线段
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(0 , 0); //注意00点的改变
ctx.lineTo(50 , 100);
ctx.stroke();
ctx.closePath();
ctx.restore(); //将旋转后的元素放回原画布
//以上顺序不可颠倒,先设置00点再旋转角度,然后画图
//旋转7中的图片
ctx.save(); //设置旋转环境
ctx.translate(10 ,280); //在异次元空间重置00点的位置,默认为画布的起点
ctx.rotate(30 * Math.PI / 180); //设置旋转角度
var img = new Image();
img.src = "beauty.jpg";
ctx.drawImage(img , 0 , 0 , 540 , 360);//注意00点的改变
ctx.restore(); //将旋转后的元素放回原画布
</script>
</body>
</html>版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u013488580/article/details/47150231