We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

CanvasGradient.addColorStop()

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

语法

void gradient.addColorStop(offset, color);

参数

offset
01之间的值,超出范围将抛出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);

标准

标准 状态 备注
HTML Living Standard
CanvasGradient.addColorStop
Living Standard  
Unknown
CanvasGradient.addColorStop
Recommendation  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

功能 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)

请参阅

文档标签和贡献者

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