为什么CanvasGradient需要CanvasRenderingContext2D来创建它?

时间:2016-09-16 19:16:15

标签: javascript canvas html5-canvas render linear-gradients

使用CanvasRenderingContext2D的HTML Canvas 2D绘图允许将fillStyle设置为CanvasGradient,如下所示:

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);

在创建和使用渐变的上下文相同的情况下;但是,这并不是必须的,因为这也有效:

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");

var renderCtx = canvas.getContext("2d");
renderCtx.fillStyle = gradient;
renderCtx.fillRect(10,10,200,100);

更令人惊讶的是,渐变所属的画布不必相同甚至显示:

var canvas = document.getElementById("canvas");

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

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

var renderCtx = canvas.getContext("2d");
renderCtx.fillStyle = gradient;
renderCtx.fillRect(10,10,200,100);

这意味着它创建的CanvasRenderingContext2D并不重要(除非我遗漏了某些内容,可能与剪辑有关?)。 为什么创建CanvasGradients的API不是静态的?

0 个答案:

没有答案