Canvas
在使用Canvas实现画板手机版时,需要检测是否支持触屏,找到了以下代码
var isTouchDevice = 'ontouchstart' in document.documentElement;
console.log(isTouchDevice)
还可以这样写
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
Canvas画板代码
<!DOCTYPE html>
<html lang="zh-CN">
<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>画板</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="100" height="100"></canvas>
<script>
let canvas = document.getElementById("canvas");
canvas.width = document.documentElement.clientWidth
canvas.height = document.documentElement.clientHeight
let ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.strokeStyle = 'none';
ctx.lineWidth = 8;
ctx.lineCap = "round";
let painting = false
let last
var isTouchDevice = 'ontouchstart' in document.documentElement;
if(isTouchDevice){
canvas.ontouchstart = (e) => {
let x = e.touches[0].clientX
let y = e.touches[0].clientY
last = [x,y]
}
canvas.ontouchmove = (e) => {
let x = e.touches[0].clientX
let y = e.touches[0].clientY
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){
drawLine(last[0],last[1],e.clientX,e.clientY)
last = [e.clientX,e.clientY]
}
}
canvas.onmouseup = () => {
painting = false
}
}
function drawLine(x1,y1,x2,y2){
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
</script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#canvas {
display: block;
}