canvas
在HTML中画图可以使用canvas元素,这里简答的总结一下:
首先通过canvas元素实现画布,代码如下:
<!Doctype html>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
//获取指定的canvas元素;
var canvas=document.getElementById("canvas);
//调用canvas元素的getContext方法访问获取2d渲染上下文。
var context=canvas.getContext('2d');
</script>
</body>
</html>
然后通过javascript来获取canvas元素,需要记住的是所有的绘画操作在canvas的context对象中进行,而不是在convas这个元素对象中,并且我们的绘画是平面的,因此是二维的。
坐标
第一个必须得了解的概念是坐标,我们通过坐标的位置来控制绘画操作的开始以及结束位置。
以10为单位的话,那个红点就是(20,20),那A就是(30,50)。
矩形
fillRect会画出实心的矩形,strokeRect会画出空心的矩形。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>绘制矩形</title>
<style>
#canvas {
background: #ddd;
}
</style>
</head>
<body>
<canvas id="canvas" width="300px" height="300px"></canvas>
<script>
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
context.strokeRect(40,20,80,80);
context.fillRect(20,120,120,60);
</script>
</body>
</html>
效果如下:
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
//开始设置路径
context.beginPath();
//设置路径原点
context.moveTo(10,20);
//设置路径终点
context.lineTo(50,20);
//绘画路径
context.stroke();
三角形
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
//开始设置路径
context.beginPath();
//设置路径原点
context.moveTo(100,50);
//设置路径终点
context.lineTo(100,200);
context.lineTo(250,200);
context.lineTo(100,50); //可以通过contex.closePath();来代替,就是自动帮我们把路径闭合。
//绘画路径
context.stroke();
context.fill(); //控制是否是实心
绘制文本
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
context.fillText('fillText',20,50);
context.strokeText('strokeText',20,100);
context.font='30px 黑体'; //控制字体的大小以及字体类型
context.fillText('strokeText2',20,200);
给图形上色
<canvas id="canvas" width="300px" height="300px"></canvas>
<script>
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
context.fillStyle='blue'; //只会其作用与它后后面的代码
context.fillRect(50,50,160,160);