移动端:
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>Canvas实现简易涂鸦板</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="box-shadow:0 5px 40px black;background-color: rgba(0,0,0,0.1)"></canvas>
<script>
canvas = document.getElementById('canvas');
if(canvas.getContext){
context = canvas.getContext('2d');
}
context.lineWidth = 5;
context.strokeStyle = '#0000ff';
canvas.addEventListener('touchstart',touchstart);
function touchstart(e){
e.preventDefault();
var touches = e.changedTouches;
var x = touches[0].clientX - canvas.offsetLeft;
var y = touches[0].clientY - canvas.offsetTop;
context.moveTo(x,y);
}
canvas.addEventListener('touchmove',touchmove);
function touchmove(e){
e.preventDefault();
var touches = e.changedTouches;
var x = touches[0].clientX - canvas.offsetLeft;
var y = touches[0].clientY - canvas.offsetTop;
context.lineTo(x,y);
context.stroke();
}
</script>
</body>
</html>
电脑端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas实现简易涂鸦板</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="box-shadow:0 5px 40px black;background-color: rgba(0,0,0,0.1)"></canvas>
<script>
canvas = document.getElementById('canvas');
if(canvas.getContext){
context = canvas.getContext('2d');
}
context.lineWidth = 5;
context.strokeStyle = '#0000ff';
canvas.onmousedown = function(e){
e.preventDefault();
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
context.moveTo(x,y);
canvas.onmousemove = function(e){
e.preventDefault();
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
context.lineTo(x,y);
context.stroke();
};
canvas.onmouseup = function(e){
canvas.onmousemove = null;
};
};
</script>
</body>
</html>