使用下面方法:
1. context.clearRect(x,y,width,height);
2. save() 和 restore()
3. getImageData()和putImageData()
第一种方法:适合按区域清空,比如整个画布。
第二种方法:就像一个保存画布状态栈,可以撤销,恢复。是一对 操作。
第三种方法: 和第二种有点相似,不是成对出现(putImageData()
可以出现多次)。
第三种用法例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>画直线</title>
<style>
canvas {
border: 1px solid;
}
</style>
</head>
<body>
<p>鼠标画直线</p>
<canvas width="800" height="600"></canvas>
<script>
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d'),
isDrag = false,
startPoint = {};
canvas.onmousedown = function () {
isDrag = true;
startPoint.x = event.x;
startPoint.y = event.y;
}
canvas.onmousemove = function() {
if(isDrag) {
context.beginPath();
context.moveTo(startPoint.x, startPoint.y);
context.lineTo(event.x, event.y);
context.stroke();
}
}
canvas.onmouseup = function() {
isDrag = false;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>画直线</title>
<style>
canvas {
border: 1px solid;
}
</style>
</head>
<body>
<p>鼠标画直线</p>
<canvas width="800" height="600"></canvas>
<script>
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d'),
isDrag = false,
startPoint = {},
restorePoint = {};
canvas.onmousedown = function () {
isDrag = true;
startPoint.x = event.x;
startPoint.y = event.y;
restorePoint = context.getImageData(0, 0, canvas.width, canvas.height);
}
canvas.onmousemove = function() {
if(isDrag) {
context.putImageData(restorePoint, 0, 0);
context.beginPath();
context.moveTo(startPoint.x, startPoint.y);
context.lineTo(event.x, event.y);
context.stroke();
}
}
canvas.onmouseup = function() {
isDrag = false;
}
</script>
</body>
</html>