demo-canvas画板
主要练习相关API
- 手机上,触摸事件
- 电脑上的点击事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width='100' height='100'></canvas>
<script>
//canvas怎么画线
let canvas = document.getElementById("canvas");
canvas.width=document.documentElement.clientWidth;
canvas.height=document.documentElement.clientHeight;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.lineWidth=8
ctx.lineCap='round'
function drawLine(x1,y1,x2,y2){
ctx.beginPath()
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
let painting=false;
let last //上一次的点
// 手机-触摸情况
var isTouchDevice = 'ontouchstart' in document.documentElement;
if(isTouchDevice){
canvas.ontouchstart = (e)=>{
console.log(1)
let x = e.touches[0].clientX
let y = e.touches[0].clientY
last = [x, y]
}
canvas.ontouchmove =(e)=>{
console.log(e)
let x = e.touches[0].clientX
let y = e.touches[0].clientY
// //console.log(x,y)
// ctx.beginPath()
// ctx.arc(x,y,10,0,2*Math.PI)
// ctx.stroke()
// ctx.fill()
drawLine(last[0],last[1],x,y)
last=[x,y]
}
}
else{// 电脑的点击事件
canvas.onmousedown=(e)=>{
painting=true;
last = [e.clientX,e.clientY]
}
canvas.onmousemove=(e)=>{
if(painting === true){
// ctx.fillRect (e.clientX -5, e.clientY-5, 10, 10);
// ctx.beginPath()
// ctx.arc(x,y,10,0,2*Math.PI)
// ctx.stroke()
// ctx.fill()
drawLine(last[0],last[1],e.clientX,e.clientY)
last=[e.clientX,e.clientY]
}
else{
console.log('nothing')
}
}
canvas.onmouseup=()=>{
painting=false;
}
}
</script>
</body>
</html>