在尝试了合成操作和在画布上绘制图像后,我现在试图删除图像和合成。我怎么做呢?

我需要清除画布重绘其他图像;这可能会持续一段时间,所以我不认为每次都画一个新的矩形是最有效的选择。


当前回答

我总是用这个

ctx.clearRect(0, 0, canvas.width, canvas.height)
window.requestAnimationFrame(functionToBeCalled)

NOTE

结合clearRect和requestAnimationFrame允许更流畅的动画,如果这是你想要的

其他回答

如果你在画线条,请确保不要忘记:

context.beginPath();

否则这些行就不会被清除。

Chrome响应良好:上下文。clearRect (x, y, w, h);正如@Pentium10所建议的,但IE9似乎完全忽略了这条指令。 IE9似乎对:canvas做出了响应。宽度= canvas.width;但它不清除线条,只是形状,图片和其他物体,除非你也使用@John Allsopp的解决方案,首先改变宽度。

如果你有一个canvas和context是这样创建的:

var canvas = document.getElementById('my-canvas');
var context = canvas.getContext('2d');

你可以使用这样的方法:

function clearCanvas(context, canvas) {
  context.clearRect(0, 0, canvas.width, canvas.height);
  var w = canvas.width;
  canvas.width = 1;
  canvas.width = w;
}

这适用于我的pieChart in chart.js

<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
function clear(context, color)
{
    var tmp = context.fillStyle;
    context.fillStyle = color;
    context.fillRect(0, 0, context.canvas.width, context.canvas.height);
    context.fillStyle = tmp;
}

这些都是如何清除标准画布的好例子,但如果你使用的是paperjs,那么这将工作:

用JavaScript定义一个全局变量:

var clearCanvas = false;

从你的PaperScript定义:

function onFrame(event){
    if(clearCanvas && project.activeLayer.hasChildren()){
        project.activeLayer.removeChildren();
        clearCanvas = false;
    }
}

现在无论你在哪里设置clearCanvas为true,它都会从屏幕上清除所有的项目。