我有以下javascript代码:
canvas = document.getElementById("cvn");
ctx = canvas.getContext("2d");
var gradient = ctx.createLinearGradient(0, 0, 100, 0);
gradient.addColorStop(0, "#00FF00");
gradient.addColorStop(0.5, "black");
,并希望引用代码后面创建的色标。我该怎么办?
我想这样使用它:
firstColorStop.setAttribute('offset', xyz);
答案 0 :(得分:0)
您可以使用变量并再次绘制画布。
怎么样呢?
<canvas id="cvn"></canvas>
<script>
var canvas = document.getElementById("cvn");
var ctx = canvas.getContext("2d");
canvas.width = 300
var blueStop = 1
var color = "white"
function drawStuff() {
var gradient = ctx.createLinearGradient(0, 0, 240, 0);
gradient.addColorStop(0, color);
gradient.addColorStop(blueStop, "blue");
ctx.fillStyle=gradient;
ctx.fillRect(20,20, 240,60);
var prop = canvas.width / 10
for (var x = prop; x < canvas.width - prop * 1.5; x += prop)
for (var y = prop; y < canvas.height; y += prop)
ctx.rect(x, y, 9, 9);
ctx.stroke();
}
drawStuff();
canvas.onmousemove = function(e) {
blueStop = e.x/(canvas.width+10)
color = (e.y > 100)? "red": "white"
drawStuff();
}
</script>
将鼠标移到画布上: