CanvasRenderingContext2D .beginPath() method of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

注意: To create a new sub-path, i.e., one matching the current canvas state, you can use CanvasRenderingContext2D.moveTo() .

句法

void ctx.beginPath();
					

范例

Creating distinct paths

This example creates two paths, each of which contains a single line.

HTML

<canvas id="canvas"></canvas>
					

JavaScript

beginPath() method is called before beginning each line, so that they may be drawn with different colors.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// First path
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.stroke();
// Second path
ctx.beginPath();
ctx.strokeStyle = 'green';
ctx.moveTo(20, 20);
ctx.lineTo(120, 120);
ctx.stroke();
					

结果

规范

规范 状态 注释
HTML 实时标准
The definition of 'CanvasRenderingContext2D.beginPath' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
beginPath Chrome Yes Edge 12 Firefox 1.5 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: