您有多种方式来完成您的任务。
到目前为止,最简单的方法是在开始绘制图表之前用背景颜色填充整个画布。 提示:您不显示代码,但如果可能,请执行此简单的解决方案。 ;=)
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)
如果你不能在开始前填写,你还有一些选择。
您可以将图表保存到另一个画布,用背景色填充整个主画布,然后将保存的图表重新绘制回主画布。
// create a second canvas and draw the chart onto it
var secondCanvas=document.createElement('canvas');
var cctx=secondCanvas.getContext('2d');
secondCanvas.width=canvas.width;
secondCanvas.height=canvas.height;
cctx.drawImage(mainCanvas,0,0);
// fill the main canvas with a background
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)
// redraw the saved chart back to the main canvas
context.drawImage(secondCanvas,0,0);
您可以使用合成来在现有像素之后绘制新图形。绘制整个背景,它将出现在现有图表的后面。
// set compositing to draw all new pixels (background) UNDER
// the existing chart pixels
context.globalCompositeOperation='destination-over';
// fill the main canvas with a background
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)
// always clean up ... reset compositing to default
context.globalCompositeOperation='source-over';