简体   繁体   中英

How to create a (moving) clip mask with trails on a canvas

I succeed in coding a moving (visible) path with trails – as in https://www.kirupa.com/canvas/follow_mouse_cursor.htm

But when I replace ctx.fill() with ctx.clip() nothing is seen … Here is my javascript code – see the complete code at 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();

I solved this in the meantime :)

  1. Had to move the background image into update()
  2. Added ctx.restore() in update()

See 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM