简体   繁体   English

画布中的clearRect问题

[英]Issues with clearRect in canvas

I'm trying to clear a part of the canvas using clearRect but it doesn't seem to work. 我正在尝试使用clearRect清除画布的一部分,但它似乎不起作用。

JSFiddle - http://jsfiddle.net/6BJaV/ 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);

In the above code i'm trying to clear the work "GRAPE" but it does not work. 在上面的代码中,我试图清除工作“ GRAPE”,但它不起作用。 Where am I going wrong ? 我要去哪里错了?

Watch the console : there are errors. 观看控制台:有错误。
You did call clearRect on the canvas, when you should call it on the context2d. 您确实应该在context2d上在画布上调用clearRect。 I think that from this point you should have all work right, for instance replacing your 3 last clearing lines with : 我认为从这一点来看,您应该一切正常,例如,用3替换最后3条清算行:

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

There are 2 erros in your code: 1- canvas isns't a context, so it has no method clearRect 2 - you shold call clear rect with these parameters to clear the word grape (110,0,110,30); 您的代码中有2个错误:1- canvas不是上下文,因此它没有方法clearRect 2-使用这些参数来保存调用clear rect来清除单词grape(110,0,110,30);

your code should be this: 您的代码应为:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM