首先canvas 只是一个容器元素,或者说提供一个画布,而真正绘制图片需要使用js脚本。
- 标签 <canvas> </canvas>
- canvas标签只有两个可选的属性 width height,如果不设置宽度和高度,默认是300*300;也可以通过css来设置宽高,但是可能会导致宽高和初始比例不一样,出现扭曲。
- 支持
<canvas>
的浏览器会只渲染<canvas>
标签,而忽略其中的替代内容。不支持<canvas>
的浏览器则 会直接渲染替代内容。 -
<canvas> 当前浏览器不支持 </canvas>
绘制形状
<canvas>只支持一种原生的图形绘制:矩形,其他图形至少需要提供一种路径
绘制矩形的三种方式:
绘制一个填充的矩形
fillRect(x, y, width, height)
绘制一个边框矩形
strokeRect(x, y, width, height)
绘制以透明矩形---注意不能使画布变透明,而是在已有的填充区域使透明部分为矩形形状
clearRect(x, y, width, height)
这里面的参数x y width height 的说明:
(x,y)指的是矩形边框左上角的坐标,相当于是起点
width height 指的是你要绘制的矩形的宽高
<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 red;
background-color: silver;
}
</style>
</head>
<body>
<canvas id="canvas" width="300px" height="300px"></canvas>
</body>
<script>
function draw1(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
//绘制矩形方式一 填充一个矩形
ctx.fillStyle = ('#bfa');
ctx.fillRect(10,10,30,40);
//方式二 绘制一个矩形边框
ctx.strokeRect(30,30,80,80);
//方式三 将一个矩形区域变得透明 ---- 不能将画布变得透明,是在填充了的区域变透明
ctx.clearRect(20,20,15,15);
}
draw();
</script></