canvas
1. 概述
canvas类似于html其他标签一样,可以直接使用(现在一般的都是可以直接使用
看起来和 元素很相像,唯一的不同就是它并没有 src 和 alt 属性。实际上, 标签只有两个属性width和height。
2. 常用方法
2.1 getContext()
类似于得到一个画布, getContext() 方法访问绘画上下文
var canvas = document.getElementById("tutorial");
var ctx = canvas.getContext("2d");
2.2 Rect(x, y, width, height)
绘制一个矩形
fillRect 绘制填充的矩阵
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d"); // 得到画笔
ctx.fillStyle = "rgb(200,0,0)"; // 画笔颜色
ctx.fillRect(10, 10, 55, 50); // 左上 大小
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect(30, 30, 55, 50);
ctx.fillStyle = 'rgb(0,200,0)';
ctx.fillRect(100,100,50,50);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>
2.3 strokeRect(x, y, width, height)
绘制一个边框矩阵
2.4 clearRect(x, y, width, height)
清除指定矩形区域,让清除部分完全透明。
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillRect(25, 25, 100, 100);
ctx.clearRect(45, 45, 60, 60);
ctx.strokeRect(50, 50, 50, 50);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>
2.5 moveTo(x, y)
将笔触移动到指定的坐标 x 以及 y 上。设置起点
2.6 lineTo(x,y)
绘制一条从当前位置到指定 x 以及 y 位置的直线。
2.7 fill()
填充
2.8 stroke()
描边
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function paint(){
const canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(10,5);// 起始点
ctx.lineTo(0,20);
ctx.lineTo(20,20);
ctx.fill()
}
}
</script>
</head>
<body onload="paint()">
<canvas width="150px" height="150px" id="canvas"></canvas>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function paint(){
const canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(10,5);// 起始点
ctx.lineTo(0,20);
ctx.lineTo(20,20);
ctx.closePath();
ctx.stroke();
}
}
</script>
</head>
<body onload="paint()">
<canvas width="150px" height="150px" id="canvas"></canvas>
</body>
</html>