rae*_*j99 5 javascript canvas erase html5-canvas global-object
这是一个非常直接和基本的问题。我认为因为这一定是一个经常发生的动作,所以必须有功能,但我找不到它?有吗?如果没有的话有人知道怎么做吗?
三种方式(至少):
要剪辑,您可以使用 beginPath、moveTo、lineTo、arcTo、... arc(任何路径构建函数)构建路径,然后调用 Clip() :路径内的部分是剪辑的部分。
不要忘记之前保存上下文并在之后恢复它(除非您想要永久剪辑)。

片段:
var context=document.getElementById('cv').getContext('2d');
context.fillStyle='#F66';
context.fillRect(150,150, 500,500); // draw big rect in red
context.save();
context.lineWidth=0; // to have precise clip
context.beginPath();
context.moveTo(100,100);
context.lineTo(200,100);
context.lineTo(200,200);
context.lineTo(100,200);
context.closePath();
context.clip();
// here we can only draw within the rect (100,100) (200,200)
context.fillStyle='#FCE'; // pink
context.fillRect(150,150, 500,500); // will get clipped
context.beginPath();
context.fillStyle = '#AAF';
context.arc(150,150, 30, 0,6.2);
context.fill(); // won't get clipped
// do not forget to restore !
context.restore();
Run Code Online (Sandbox Code Playgroud)
完整的例子在这里:
https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html
请注意,较暗不起作用(但无论如何它都没有用,只需使用正常模式=低不透明度(0.2)的源覆盖和黑色的fillRect)。
另一种选择是使用临时画布进行绘图。这非常简单,特别是当您创建小型辅助函数时。
函数 createCanvas(w,h){
var cv = document.createElement('canvas');
CV宽度;cv.height = 高度;
返回简历;
}
(无论如何,您有兴趣,您可以查看我的小库,以轻松使用画布: https://github.com/gamealchemist/CanvasLib/blob/master/canvasLib.js)