如何删除以前的画布形状时,我再次调用画布

how to remove the previous canvas shape when i call the canvas again?

本文关键字:布形状 调用 何删除 删除      更新时间:2023-09-26

当我按下下一个按钮时,我用画布绘制一个随机大小的正方形我调用canvasarea()函数,它绘制了一个随机大小的正方形,但我遇到了一个问题,因为之前的正方形还在画布上,还有之前的正方形,等等。解决方案是什么?

function canvasarea(){
var canvas = document.getElementById('square');
var context = canvas.getContext('2d');
context.beginPath();
var Size=getSize();
context.rect(10,10, 5*Size, 5*Size);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();

        }
function getSize(){
var min = 30;
var max = 40;
var size = Math.floor(Math.random() * (max - min + 1) + min)
document.getElementById("sideSize").innerHTML=size;
return size;
}

在绘制形状之前,使用以下方法清除画布:

context.clearRect(0, 0, canvas.width, canvas.height);

这是CanvasRenderingContext2D.clearRect()的文档

我创建了2个函数,第一个是清除画布,第二个是用与原始画布相同的属性重新绘制画布,但大小不同

  function canvasarea(){
  var canvas = document.getElementById('square');
  var context = canvas.getContext('2d');
  context.beginPath();
  var Size=getSize();
  context.rect(10,10, 5*Size, 5*Size);
  context.fillStyle = 'red';
  context.fill();
  context.lineWidth =7;
  context.strokeStyle = 'black';
  clear(canvas);
  redraw();
        }
 function clear(a){
 a.getContext('2d').clearRect(0,0,a.width,a.height);
 }
 function redraw(){
 var canvas = document.getElementById('square');
 var context = canvas.getContext('2d');
 context.beginPath();
 var Size=getSize(); 
 context.rect(10,10, 5*Size, 5*Size);
 context.fillStyle = 'red';
 context.fill();
 context.lineWidth = 7;
 context.strokeStyle = 'black';

      }