清空canvas画布内容
1、重置宽或高
由于canvas每当高度或宽度被重设时,画布内容就会被清空,因此可以用以下方法清空:(此方法仅限需要清除全部内容的情况)
var c=document.getElementById("myCanvas"); c.width=c.width;
2、clearRect
1 var c=document.getElementById("myCanvas"); 2 var ctx=c.getContext("2d"); 3 ctx.fillStyle="red"; 4 ctx.fillRect(0,0,300,150); 5 ctx.clearRect(20,20,100,50);
3、globalCompositeOperation
引用globalCompositeOperation()函数,这个函数是用来在画布上组合颜色,我们可以利用这个原理,叠加(数学上的"或"原理)来制作橡皮。
首先看看 globalCompositeOperation属性可以设置的值有哪些,分别是什么效果:
值 | 描述 |
---|---|
source-over | 默认。在目标图像上显示源图像。 |
source-atop | 在目标图像顶部显示源图像。源图像位于目标图像之外的部分是不可见的。 |
source-in | 在目标图像中显示源图像。只有目标图像内的源图像部分会显示,目标图像是透明的。 |
source-out | 在目标图像之外显示源图像。只会显示目标图像之外源图像部分,目标图像是透明的。 |
destination-over | 在源图像上方显示目标图像。 |
destination-atop | 在源图像顶部显示目标图像。源图像之外的目标图像部分不会被显示。 |
destination-in | 在源图像中显示目标图像。只有源图像内的目标图像部分会被显示,源图像是透明的。 |
destination-out | 在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。 |
lighter | 显示源图像 + 目标图像。 |
copy | 显示源图像。忽略目标图像。 |
xor | 使用异或操作对源图像与目标图像进行组合。 |
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <style> 5 canvas 6 { 7 border:1px solid #d3d3d3; 8 margin-right:10px; 9 margin-bottom:20px; 10 } 11 </style> 12 </head> 13 <body> 14 15 <script> 16 17 var gco=new Array(); 18 gco.push("source-atop"); 19 gco.push("source-in"); 20 gco.push("source-out"); 21 gco.push("source-over"); 22 gco.push("destination-atop"); 23 gco.push("destination-in"); 24 gco.push("destination-out"); 25 gco.push("destination-over"); 26 gco.push("lighter"); 27 gco.push("copy"); 28 gco.push("xor"); 29 for (n=0;n<g