我想在我的立方曲线上添加线性渐变,同时在移动鼠标时改变它的位置。但不知怎的,它不会起作用。如果我停止改变它的位置并将其固定在我的屏幕上,它就会起作用。
document.addEventListener("DOMContentLoaded", function() {
var canvas = document.querySelector("canvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");
ctx.fillStyle = "#CCC";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//var prev = {};
var mouse = {};
window.addEventListener("mousemove", function(e) {
//prev.x = mouse.x;
//prev.y = mouse.y;
mouse.x = e.pageX;
mouse.y = e.pageY;
});
function draw() {
ctx.fillStyle = "#CCC";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var grad = ctx.createLinearGradient(50, 50, 150, 150);
grad.addColorStop(0, "yellow");
grad.addColorStop(0.5, "white");
grad.addColorStop(1, "orange");
ctx.lineWidth = 10;
ctx.lineJoin = "round";
ctx.strokeStyle = grad;
ctx.beginPath();
ctx.moveTo((canvas.width / 2), (canvas.height / 2));
ctx.quadraticCurveTo(((canvas.width / 2) - 100), (canvas.height / 2 + 100), (mouse.x), (mouse.y));
ctx.stroke()
};
window.addEventListener("mousemove", draw);
});
答案 0 :(得分:0)
当我从DOMContentLoaded事件函数中删除它时,它在这个jsfiddle中正常工作:https://jsfiddle.net/wboq6bsk/
var canvas = document.querySelector("canvas");
canvas.id= 'test'
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");
ctx.fillStyle = "#CCC";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var mouse = {};
window.addEventListener("mousemove", function(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
});
function draw(){
console.log('dra');
ctx.fillStyle = "#CCC";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var grad = ctx.createLinearGradient(50, 50, 150, 150);
grad.addColorStop(0, "yellow");
grad.addColorStop(0.5, "white");
grad.addColorStop(1, "orange");
ctx.lineWidth = 10;
ctx.lineJoin = "round";
ctx.strokeStyle = grad;
ctx.beginPath();
ctx.moveTo((canvas.width/2), (canvas.height/2));
ctx.quadraticCurveTo(((canvas.width/2)-100), (canvas.height/2+100), (mouse.x), (mouse.y));
ctx.stroke()
}
window.addEventListener("mousemove", draw);
除非你的意思是你的渐变,否则它不随曲线移动,但是现在它具有正常的行为。在每次绘制时创建渐变时,您可以通过传递鼠标位置来获得渐变。