1 创建canvas <canvas id="cas" width="600" height="300":> 您的浏览器不支持html5的canvas,请更换浏览器! </canvas> css中定义canvas的宽高具有拉伸效果!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
body {
text-align: center;
}
canvas {
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="cas" width="600" height="300">
您的浏览器不支持canvas画布...
</canvas>
<script>
var cas = document.querySelector(‘#cas‘)
var ctx = cas.getContext(‘2d‘) // canvas对象调用getContext方法 这是一个绘图环境
// 1按下画图 开关 isDown = true
var isDown = false
cas.addEventListener(‘mousedown‘,function (e) {
isDown = true
ctx.beginPath()
},false)
cas.addEventListener(‘mousemove‘,function (e) {
if (isDown) {
let x = e.layerX
let y = e.layerY
ctx.lineTo(x,y)
ctx.stroke()
}
},false)
cas.addEventListener(‘mouseup‘,function () {
isDown = false
},false)
cas.addEventListener(‘mouseout‘,function () {
isDown = false
},false)
</script>
</body>
</html>