标签:
<canvas> 标签只是图形容器,您必须使用脚本来绘制图形。默认情况下该矩形区域宽为300像素,高为150像素,设置宽高必须在canvas标签内部,不能加单位px。
大多数 Canvas 绘图 API 都没有定义在 <canvas> 元素本身上,而是定义在通过画布的 getContext() 方法获得的一个“绘图环境”对象上。
注意:样式中的宽高是对画布等比例缩放,画布的内容也相应的缩放
moveTo(x, y)方法设置线段的起点,lineTo(x, y)方法设置线段的终点,stroke()方法用来给透明的线段着色。 默认是黑色。beginPath()重置路径,closePath()创建从当前点到起始点的路径
现在用路径画一个矩形
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
canvas {
border: 1px solid black;
width: 1000px;
}
</style>
</head>
<body>
<canvas id="cvs" width="1000" height="500" ></canvas>
<script>
var cvs = document.getElementById(‘cvs‘); // 获取Canvas标签
// 绘制2d图形,要传递2d作为参数
// 绘制3d图形,要传递webgl作为参数
var ctx = cvs.getContext(‘2d‘);
//这里使用的是矩形函数的封装
function strokeRect(ctx, x, y, w, h) {
// ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + w, y);
ctx.lineTo(x + w, y + h);
ctx.lineTo(x, y + h);
ctx.lineTo(x, y);
ctx.stroke();
}
strokeRect(ctx,100,100,150,150);//在画布中绘制一个起点位置在(100,100),宽高各为150px的矩形
</script>
</body>
</html>
绘制矩形:
rect(x,y,w,h)
fillRect(x,y,w,h)绘制被填充的矩形 默认黑色 自己不渲染,需使用fill()或stroke()
strokeRect(x,y,w,h)绘制带边框的矩形 默认黑色 自己不渲染,需使用fill()或stroke()
设置属性:
fillStyle:填充颜色(注意顺序)
strokeStyle:线条颜色
lineWidth:线宽
lineJoin:边界样式
lineCap:端点样式
配合css一起使用
fillText(string, x, y) 用来绘制文本,它的三个参数分别为文本内容、起点的x坐标、y坐标
与此类似的还有strokeText方法,用来添加空心字。
fillText方法不支持文本断行,即所有文本出现在一行内。所以,如果要生成多行文本,只有调用多次fillText方法。
不封装做个demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="cvs" width="1000" height="500"></canvas>
<script>
var cvs = document.getElementById(‘cvs‘);
var ctx = cvs.getContext(‘2d‘);
ctx.fillRect(50,50,50,50);
var num = 0;
setInterval(function(){
num++;
ctx.clearRect(0,0,1000,500);
ctx.fillRect(num,num,50,50);
},25)
</script>
</body>
</html>
以框架形式封装呈现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="cvs" width="1000" height="500"></canvas>
<script>
var cvs = document.getElementById(‘cvs‘);
var ctx = cvs.getContext(‘2d‘);
// 矩形绘制函数的封装
function strokeRect(ctx, x, y, w, h) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + w, y);
ctx.lineTo(x + w, y + h);
ctx.lineTo(x, y + h);
ctx.lineTo(x, y);
ctx.stroke();
}
//构造函数
function Rect(ctx, x, y, w, h) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
//构造函数的原型对象添加方法
Rect.prototype.draw = function(){
strokeRect(this.ctx,this.x,this.y,this.w,this.h);
};
var rect = new Rect(ctx,50,50,50,50);
var displayObjects = [];
displayObjects.push(rect);
setInterval(function(){
ctx.clearRect(0,0,1000,500);//在每次执行定时器时清除整个画布
rect.x = rect.x+1;
displayObjects.forEach(function(displayObject){
displayObject.draw();
})
},25)
</script>
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/goweb/p/5415186.html