canvas使用(一)
在html页面创建canvas标签,通过内联样式设置canvas宽高(不通过css样式设置,此种方式设置canvas里面会等比例缩放)
<canvas id="myCanvas" width="400px" height="400px">如果浏览器不支持canvas,则会显示这里的细腻些</canvas>
canvas主要通过js进行绘制:
首先在js中获得canvas,通过getContext()获得2d对象
var drawing = document.getElementById("myCanvas");
var context = drawing.getContext("2d");
1.矩形的绘制
描边矩形:strokeRect(左上角x,左上角Y,宽,高) strokeStyle 设置颜色 context.strokeStyle = "green"; context.strokeRect(30,30,100,100);
if(context){
//描边绿矩形
context.strokeStyle = "green";
//左上角坐标为(30,30) 宽高分别为100,100
context.strokeRect(30,30,100,100);
}
// 填充个红矩形:fillRect(左上角x,左上角Y,宽,高)
fillStyle 设置颜色
context.fillStyle = “red”;
context.fillRect(10,50,100,100);
if(context){
// 填充个红矩形
//设置矩形填充色为红色
context.fillStyle = "red";
//设置矩形左上角坐标(10,50) 宽高分别为100,100
context.fillRect(10,50,100,100);
}
改变矩形填充色为黄色,矩形左上角坐标为(100,100)
//擦除矩形 clearRect(横坐标,纵坐标,宽,高) context.clearRect(0,0,400,400);
清楚全部canvas上图形
// 填充个红矩形
context.fillStyle = "green";
context.fillRect(10,50,80,80);
//擦除矩形
context.clearRect(0,0,400,400);
清楚指定区域的图形
清楚从canvas上(0,0)坐标开始,宽高分别为20,100的矩形区域的图形:
// 填充个红矩形
context.fillStyle = "green";
context.fillRect(10,50,80,80);
//擦除矩形
context.clearRect(0,0,40,100);
2.路径的绘制
// 设置落笔点:moveTo(横坐标x,纵坐标y)
设置路径:lineTo(横坐标x,纵坐标y)
设置颜色:strokeStyle
对路径进行绘制:stroke() 不适用该函数,canvas看不到上述绘制的路径context.moveTo(50,50); context.lineTo(50,100);
context.strokeStyle = “red”; context.stroke();
// 设置落笔点:moveTo(横坐标x,纵坐标y)
context.moveTo(50,50);
// 设置路径:lineTo(横坐标x,纵坐标y)
context.lineTo(50,100);
// 设置轨迹颜色:strokeStyle
context.strokeStyle = "red";
// 对路径进行绘制:stroke() 不适用该函数,canvas看不到上述绘制的路径
context.stroke();