// Store the current transformation matrixcontext.save();
// Use the identity matrix while clearing the canvascontext.setTransform(1, 0, 0, 1, 0, 0);context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transformcontext.restore();
CanvasRenderingContext2D.prototype.clear =CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {if (preserveTransform) {this.save();this.setTransform(1, 0, 0, 1, 0, 0);}
this.clearRect(0, 0, this.canvas.width, this.canvas.height);
if (preserveTransform) {this.restore();}};
用法:
window.onload = function () {var canvas = document.getElementById('canvasId');var context = canvas.getContext('2d');
// do some drawingcontext.clear();
// do some more drawingcontext.setTransform(-1, 0, 0, 1, 200, 200);// do some drawing with the new transformcontext.clear(true);// draw more, still using the preserved transform};
// assuming background color = white and "eraseAlpha" is a value from 0 to 1.myContext.fillStyle = "rgba(255, 255, 255, " + eraseAlpha + ")";myContext.fillRect(0, 0, w, h);
canvas = document.getElementById("canvas");c = canvas.getContext("2d");
//... some drawing here
i = c.createImageData(canvas.width, canvas.height);c.putImageData(i, 0, 0); // clear context by putting empty image data
<div class="pie_nut" id="pieChartContainer"><canvas id="pieChart" height="5" width="6"></canvas></div>
$('#pieChartContainer').html(''); //remove canvas from container$('#pieChartContainer').html('<canvas id="pieChart" height="5" width="6"></canvas>'); //add it back to the container