<!DOCTYPE html>
<html lang="zh">
<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>
#mycanvas{
border: 1px dashed gray;
}
</style>
</head>
<body>
<div id="container">
<canvas id="mycanvas" width="1000px" height="800px"></canvas>
</div>
<script>
let dom = document.getElementById('mycanvas');
let ctx = dom.getContext('2d');
let flag = false;
dom.addEventListener('mousedown', e =>{
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.lineWidth = 10;
ctx.moveTo(e.offsetX, e.offsetY);
flag= true;
})
dom.addEventListener('mousemove', e => {
if(flag){
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
})
dom.addEventListener('mouseup', e => {
//ctx.closePath();
ctx.stroke();
flag = false;
})
</script>
</body>
</html>
|