Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

CanvasGradient.addColorStop()

CanvasGradient.addColorStop() 方法添加一个由偏移值和颜色值指定的断点到渐变。如果偏移值不在0到1之间,将抛出INDEX_SIZE_ERR错误,如果颜色值不能被解析为有效的CSS颜色值 <color>,将抛出SYNTAX_ERR错误。

语法

void gradient.addColorStop(offset, color);

参数

offset
0到1之间的值,超出范围将抛出INDEX_SIZE_ERR错误
color
CSS颜色值 <color>如果颜色值不能被解析为有效的CSS颜色值 <color>,将抛出SYNTAX_ERR错误。

示例

使用addColorStop方法

一个使用CanvasGradient对象的addColorStop 方法的简单例子

HTML

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

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var gradient = ctx.createLinearGradient(0,0,200,0);
gradient.addColorStop(0,"green");
gradient.addColorStop(1,"white");
ctx.fillStyle = gradient;
ctx.fillRect(10,10,200,100);

编辑以下代码可看到画布变化:

Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
var gradient = ctx.createLinearGradient(0,0,200,0);
gradient.addColorStop(0,"green");
gradient.addColorStop(1,"white");
ctx.fillStyle = gradient;
ctx.fillRect(10,10,200,100);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener("click", function() {
  textarea.focus();
})

textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);

标准

标准 状态 备注
WHATWG HTML Living Standard
CanvasGradient.addColorStop
Living Standard  
HTML Canvas 2D Context (W3C)
CanvasGradient.addColorStop
Recommendation  

浏览器兼容性

功能 Chrome Firefox (Gecko) Internet Explorer Opera Safari
基本支持 (Yes) (Yes) (Yes) (Yes) (Yes)
功能 Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基本支持 (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

请参阅

文档标签和贡献者

 此页面的贡献者: Sebastianz, teoli, cuixiping
 最后编辑者: Sebastianz,