1.canvas画直线
<body>
<canvas id="canvas" width="400px" height="400px">版本过低!</canvas>
</body>
<script>
//1.获取画布
var canvas = document.getElementById('canvas')
//2.获取画布上下文
var ctx = canvas.getContext('2d');
//3.开启一条路径
ctx.beginPath()
//4.确定起始点
ctx.moveTo(100,100)
//5.确定结束点
ctx.lineTo(300,100)
//在着色之前设置线
ctx.strokeStyle='skyblue'
// 线宽
ctx.lineWidth=5;
// 6.着色
ctx.stroke()
// 7.结束路径
ctx.closePath()
</script>
2.封装
<body>
<canvas id="canvas" width="400px" height="400px">版本过低!</canvas>
</body>
<script>
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
drawLine(100,100,300,100,'pink',2)
drawLine(300,100,300,300,'purple',2)
drawLine(100,300,300,300,'skyblue',2)
drawLine(100,100,100,300,'green',2)
function drawLine(x1,y1,x2,y2,color,width){
ctx.beginPath()
ctx.moveTo(x1,y1)
ctx.lineTo(x2,y2)
ctx.strokeStyle=color
ctx.strokeStyle=color
ctx.lineWidth=width
ctx.stroke()
ctx.closePath()
}
</script>
3.实心 空心 矩形
<body>
<canvas id="canvas" width="400px" height="400px">版本过低!</canvas>
</body>
<script>
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
// 画矩形
ctx.rect(50,50,300,200)
// 先填充后描边
// 填充
ctx.fillStyle='skyblue'
ctx.fill()
// 描边
ctx.strokeStyle='pink'
ctx.lineWidth=5
ctx.stroke()
// 实心矩形
ctx.fillStyle='pink'
ctx.fillRect(50,300,100,100)
// 空心矩形
ctx.fillStyle='blue'
ctx.lineWidth=2
ctx.strokeRect(250,300,100,100)
</script>
4.绘制图片
var img =new Image()
img.src='下载.png'
// onload加载成功触发
// onerror加载失败触发
img.onload=function(){
// 图片宽高
// console.log(img.height,img.width);
//img对象,起始位置
// ctx.drawImage(img,0,0)
//img对象,起始位置,设置图片大小
ctx.drawImage(img,0,0,200,200)
// 剪切图片,定位剪切的位置
//img对象,切起始位置,设置切图片大小,图片放起始位置,设置切图片大小
// ctx.drawImage(img,70,70,270,260,0,0,400,400)
}