--- title: CanvasRenderingContext2D.beginPath() slug: Web/API/CanvasRenderingContext2D/beginPath translation_of: Web/API/CanvasRenderingContext2D/beginPath ---
{{APIRef}}

CanvasRenderingContext2D.beginPath() 是 Canvas 2D API 通过清空子路径列表开始一个新路径的方法。 当你想创建一个新的路径时,调用此方法。

语法

void ctx.beginPath();

示例

使用 beginPath 方法

这是一段受用 beginPath 方法的简单的代码片段。

HTML

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

JavaScript

var canvas = document.getElementById("canvas");
var 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();

修改下面的代码并在线查看 canvas 的变化:

{{ EmbedLiveSample('Playable_code', 700, 460) }}

规范描述

Specification Status Comment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-beginpath", "CanvasRenderingContext2D.beginPath")}} {{Spec2('HTML WHATWG')}}  

浏览器兼容性

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

参见