如何在画布上创建带有轨迹的(移动的)剪贴蒙版

时间:2019-07-10 16:33:47

标签: javascript html html5-canvas

我成功地将带有尾部的移动(可见)路径编码为- https://www.kirupa.com/canvas/follow_mouse_cursor.htm

但是当我用ctx.clip()替换ctx.fill()时,什么也看不到……这是我的JavaScript代码–请参见https://codepen.io/j-raff/pen/JQxOPj

的完整代码
var jrCanvas = document.getElementById("jr-canvas");
var ctx = jrCanvas.getContext("2d");
var mouseX, mouseY;

var bgImageOnCanvas = new Image();
bgImageOnCanvas.src =
  "http://www.graffik.de/wp-content/uploads/forgethers-abgesang-01.png";

bgImageOnCanvas.onload = function() {
  ctx.drawImage(bgImageOnCanvas, 0, 0);
};

jrCanvas.addEventListener("mousemove", function(e){
  mouseX = e.clientX;
  mouseY = e.clientY;
}, false);

function update() {
  ctx.save();
  ctx.beginPath();
  ctx.arc(mouseX, mouseY, 50, 0, Math.PI * 2, true);
  ctx.clip();
  requestAnimationFrame(update);
}
update();

1 个答案:

答案 0 :(得分:0)

与此同时我解决了这个问题:)

  1. 必须将背景图像移动到update()
  2. 在update()中添加了ctx.restore()

请参见https://codepen.io/j-raff/pen/zVepOK

var jrCanvas = document.getElementById("jr-canvas");
var ctx = jrCanvas.getContext("2d");
var mouseX, mouseY;
var x, y;

var bgImageOnCanvas = new Image();
bgImageOnCanvas.src =
  "http://www.graffik.de/wp-content/uploads/forgethers-abgesang-01.png";

jrCanvas.addEventListener("mousemove", function(e){
  mouseX = e.clientX;
  mouseY = e.clientY;
  update();
}, false);

function update() {
  ctx.save();
  ctx.beginPath();
  ctx.arc(mouseX, mouseY, 50, 0, Math.PI * 2, true);
  ctx.clip();
  ctx.drawImage(bgImageOnCanvas, 0, 0);
  ctx.restore();
}