我试过了:
cx.fillRect()
但: 它对我不起作用,我只需要重新加载画布而不是页面。
这是我的代码:
var canvas = document.getElementById('canvas');
var cx = canvas.getContext('2d');
canvas.height = 300;
canvas.width = 600;
function branch(length, angle, scale) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
cx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
cx.fill();
cx.fillRect(0, 0, 1, length);
if (length < 8) return;
cx.save();
cx.translate(0, length);
cx.rotate(-angle);
branch(length * scale, angle, scale);
cx.rotate(2 * angle);
branch(length * scale, angle, scale);
cx.restore();
}
cx.translate(300, 2);
function change() {
a = Math.random();
branch(60, a, 0.8);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
canvas{
margin: 100px auto;
position: absolute;
left: 0;right: 0;
top: 0;bottom: 0;
border: 1px solid #ccc;
background-color: #ECEFF1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<button onclick="change()">Change</button>
<script src="main.js"></script>
</body>
</html>
这是我运行代码并单击按钮时的屏幕:
答案 0 :(得分:0)
您可以尝试:
cx.clearRect(0, 0, 300, 600)