canvas属性
HTML5 canvas 元素用于图形的绘制,通过JavaScript来完成.
canvas 标签只是图形容器,您必须使用脚本来绘制图形。
你可以通过多种方法使用 canvas 绘制路径,盒、圆、字符以及添加图像。
使用canvas绘画一条直线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function() {
let canvas = document.querySelector('canvas'); //获取canvas对象
let ctx = canvas.getContext('2d'); //创建一个画布
ctx.beginPath(); //开始新的一条路径
ctx.moveTo(100, 100); //起始地点
ctx.lineTo(400, 100); //结束地点
ctx.stroke(); //着色
ctx.closePath(); //结束路径
}
</script>
</head>
<body>
<canvas width="500px" height="500px">
您的浏览器版本过低,请升级浏览器或者使用chrome打开<!--在低版本的情况下例如ie7的时候会把canvas当成一个标签输出里面的内容-->
</canvas>
</body>
</html>
使用canvas画一个矩形
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
<script>
window.onload = function() {
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
//上边横长线
ctx.beginPath();
ctx.moveTo(400, 100);
ctx.lineTo(100, 100);
ctx.strokeStyle = "red";//设置颜色可以为16进制、rgba、英文
ctx.lineWidth = 8;//线宽
ctx.stroke();
//左边竖长线
ctx.moveTo(100, 100);
ctx.lineTo(100, 400);
ctx.strokeStyle = "skyblue";
ctx.lineWidth = 8;
ctx.stroke();
//下边横长线
ctx.moveTo(100, 400);
ctx.lineTo(400, 400);
ctx.strokeStyle = "yellow";
ctx.linewidth = 8;
ctx.stroke();
//右边竖长线
ctx.moveTo(400, 400);
ctx.lineTo(400, 100);
ctx.strokeStyle = "red";
ctx.linewidth = 8;
ctx.stroke();
ctx.closePath();
}
</script>
</head>
<body>
<canvas width="500px" height="500px"></canvas>
</body>
</html>
写的有些重复,后面会更新function传值写法
Comments | NOTHING