canvas中clearRect的问题

时间:2013-11-18 15:18:41

标签: javascript html5 html5-canvas

我正在尝试使用clearRect清除画布的一部分,但它似乎不起作用。

JSFiddle - http://jsfiddle.net/6BJaV/

var canvasWrapper = document.createElement('canvas');
var canvasWrapperContext = canvasWrapper.getContext('2d'); 
canvasWrapper.width = 300;
canvasWrapper.height = 300;


var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 300;
canvasContext.font = "bold 20pt arial";
canvasContext.fillText("APPLE",0,30);
canvasContext.fillText("GRAPE",110,30);

canvasWrapperContext.drawImage(canvas,0,0,canvas.width,canvas.height);

document.body.appendChild(canvasWrapper);

//clear a part of canvas
canvas.clearRect(110,30,110,30);   //clear the text grape
canvasWrapper.clearRect(0,0,canvasWrapper.width,canvasWrapper.height);
canvasWrapperContext.drawImage(canvas,0,0,canvas.width,canvas.height);

在上面的代码中我试图清除工作“GRAPE”,但它不起作用。我哪里错了?

2 个答案:

答案 0 :(得分:0)

观看控制台:有错误。
你应该在canvas2d上调用clearRect,你应该在context2d上调用它。 我认为从这一点来说,你应该把所有工作都做好 用以下内容替换最后3条清算行:

 canvasWrapperContext.clearRect(0,0,210,30);  

答案 1 :(得分:0)

您的代码中有2个错误: 1- canvas不是上下文,所以它没有clearRect方法 2 - 你用这些参数调用clear rect来清除葡萄(110,0,110,30);

你的代码应该是这样的:

var canvasWrapper = document.createElement('canvas');
var canvasWrapperContext = canvasWrapper.getContext('2d'); 
canvasWrapper.width = 300;
canvasWrapper.height = 300;


var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 300;
canvasContext.font = "bold 20pt arial";
canvasContext.fillText("APPLE",0,30);
canvasContext.fillText("GRAPE",110,30);

canvasWrapperContext.drawImage(canvas,0,0,canvas.width,canvas.height);

document.body.appendChild(canvasWrapper);

canvasWrapperContext.clearRect(110,0,110,30);
canvasContext.clearRect(110,30,110,30);