使用JavaScript在画布上绘制鼠标移动时的透明图像

时间:2015-11-10 22:27:12

标签: javascript html canvas html5-canvas

由SVG图像组成的棋盘游戏在HTML画布中绘制。当鼠标悬停在画布上时,我想用鼠标移动透明游戏块图像。我想这样做,而不必每次移动鼠标时迭代游戏矩阵。我能提出的唯一方法如下所示;但是,绘制图像的最后位置仍然存在,从而产生这种效果:

Draw game piece image

实现这一目标的最佳方法是什么?



canvas.addEventListener("mousemove", drawPieceAtMouse, false);

function drawPieceAtMouse(event) {
  var rect = canvas.getBoundingClientRect();
  var x = event.clientX - rect.left;
  var y = event.clientY - rect.top;
  context.save();
  context.globalAlpha = 0.4;
  context.drawImage(players[turn].piece, x-25, y-25, 50, 50);
  context.restore();
}




1 个答案:

答案 0 :(得分:0)

使用此代码

canvas.addEventListener("mousemove", drawPieceAtMouse, false);


var canvasimg = new Image();
function updatecanvasimage(){
canvasimg = new Image();
canvasimg.src = canvas.toDataURL("image/png");
}
updatecanvasimage()//call this when you want changes to stay on the canvas

function drawPieceAtMouse(event) {
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
context.drawImage(canvasimg,0 , 0,canvas.width,canvas.height);
context.globalAlpha = 0.4;
context.drawImage(players[turn].piece, x-25, y-25, 50, 50);
}