我在页面加载时有一个 Canvas 矩形形状。我的要求是,我想在鼠标悬停时在矩形上画一个圆圈,并想在离开矩形后将其删除。现在我可以用鼠标在矩形上画一个圆圈。但离开矩形后我无法删除该圆圈。我保存画圆之前的状态并在画圆之后恢复状态。但我的代码不起作用。有人请告诉我,我做错了什么吗?
RectMouseMove: function (evt) {
this.ctx.save();
this.ctx.beginPath();
this.ctx.rect(this.X, this.Y, this.Width, this.Height);
this.ctx.clip();
this.drawCircle(this.options);
this.ctx.restore();
},
drawCircle: function (options) {
this.ctx.beginPath();
this.ctx.arc(options.cx, options.cy, options.r, 0, 2 * Math.PI);
this.ctx.fillStyle = options.fill;
this.ctx.globalAlpha = options.opacity;
this.ctx.fill();
this.ctx.lineWidth = options["stroke-width"];
this.ctx.strokeStyle = options.stroke;
this.ctx.stroke();
}
谢谢, 巴拉蒂。
最佳答案
调用restore
不会恢复到调用save
时 Canvas 的状态。换句话说,它不会删除绘制到 Canvas 上的任何变换。 save
的作用是将当前设置推送到堆栈顶部,因此当您调用 restore
时,它会弹出并使用这些设置。
示例:
var c = document.getElementById('canvas'),
ctx = c.getContext('2d');
function draw(e) {
ctx.fillStyle = '#09F';
ctx.fillRect(e.x, e.y, 10, 10);
}
function reset() {
ctx.restore();
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, c.width, c.height);
ctx.save();
}
reset();
c.addEventListener('mousemove', draw);
c.addEventListener('mouseleave', reset);
关于javascript - 鼠标移动绘制圆圈后保存并恢复 Canvas 矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25906468/