How to remove the previous draw image from canvas

天大地大妈咪最大 提交于 2020-01-03 06:21:09

问题


I have been trying to print arc in the html page. How can i remove the already drawn arch from the page?. i have written the below code.

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="1200" height="1000"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
/*ctx.beginPath();
ctx.arc(600,500,20, 0.5*Math.PI,2*Math.PI);
ctx.stroke();

ctx.beginPath();
ctx.arc(600,500,40, 0.5*Math.PI,2*Math.PI);
ctx.stroke();
*/
var radius=20;
for (i=0; i<10; i++)
{
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(600,500,radius, 0.5*Math.PI, 2*Math.PI);
  ctx.stroke();
  radius= radius+30;
}


</script> 

</body>
</html>

How can i achieve this?.


回答1:


A bitmap is not a vector graphic. You cannot simply remove or modify things you've drawn previously. By drawing on a canvas you modify the pixel color values of its image data. If you need to undo things you have to maintain a separate data structure with the relevant data yourself.

For example you could create a copy of the image data before drawing something. Then you could return to this snapshot afterwards. HTMLCanvasElement#toDataURL returns the complete image as an url which you can use as the src of an image. Later you can draw this image on the canvas to revert all subsequent changes. HTMLCanvasElement#toBlob does about the same but it returns a blob. This might consume less memory but it's a little more inconvenient to use. The most convenient method is CanvasRenderingContext2D#getImageData. You can even use it to copy only a small part of the image. This is useful if you have a big canvas but only modify pixels in a small region.

Another way to make modifications undoable is by maintaining a detailed list of your steps. For example whenever you draw an arc you store the exact parameters as one entry in the list. steps.push({type: 'stroke', style: 'rgb(0,0,0)', shapes: [{type: 'arc', x: 600, y: 500, radius: radius, from: 0.5 * Math.PI, to: 2 * Math.PI}]}) You can remove, rearrange or modify the elements in this list any way you like and have all necessary information to draw the resulting image from scratch. Basically you've implemented just another vector graphic library.




回答2:


Call clearRect method:

ctx.clearRect(0, 0, 1200, 1000)

The four arguments are:

  1. axis-X of left top corner of the area to wipe
  2. axis-Y of left top corner of the area to wipe
  3. width of the area to wipe
  4. height of the area to wipe

So with this method, you could wipe either the whole canvas or just a certain part of it.



来源:https://stackoverflow.com/questions/27458542/how-to-remove-the-previous-draw-image-from-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!