javascript 我怎么能把多个物体放在同一个画布上?

h4cxqtbf  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(126)

我正在创建一个网页,你动态地画多个矩形.我可以画单个对象,但是一旦我试图画另一个,前一个消失了.我试图用保存来保存状态()并恢复(),而且好像不能放在这里,save方法放在mouseup事件里面,restore方法在mousedown事件里面调用,这不符合逻辑吗?任何帮助或建议将不胜感激。

const canvas = document.getElementById("circle"),
   ctx = canvas.getContext("2d"),
   circle = {},
   drag = false,
   circleMade = false,
   mouseMoved = false;

function draw() {
   ctx.beginPath();
   ctx.arc(circle.X, circle.Y, circle.radius, 0, 2.0 * Math.PI);
   ctx.stroke();

}

function mouseDown(e) {
   ctx.restore();
   circle.startX = e.pageX - this.offsetLeft;
   circle.startY = e.pageY - this.offsetTop;

   circle.X = circle.startX;
   circle.Y = circle.startY;

   if (!circleMade) {
       circle.radius = 0;
   }

   drag = true;
}

function mouseUp() {
   drag = false;
   circleMade = true;

   if (!mouseMoved) {
       circle = {};
       circleMade = false;
       ctx.clearRect(0, 0, canvas.width, canvas.height);
   }

   mouseMoved = false;
   ctx.save();
}

function mouseMove(e) {
   if (drag) {
       mouseMoved = true;
       circle.X = e.pageX - this.offsetLeft;
       circle.Y = e.pageY - this.offsetTop;
       if (!circleMade) {
           circle.radius = Math.sqrt(Math.pow((circle.X - circle.startX), 2) + Math.pow((circle.Y - circle.startY), 2));
       }
       ctx.clearRect(0, 0, canvas.width, canvas.height);
       draw();

   }
}

function init() {
   canvas.addEventListener('mousedown', mouseDown, false);
   canvas.addEventListener('mouseup', mouseUp, false);
   canvas.addEventListener('mousemove', mouseMove, false);

}

init();
guykilcj

guykilcj1#

你需要保存关于你在一个单独的对象中画什么的信息,每次你在画布上画你将擦除并重画新的对象.所以当你清除矩形然后画你正在清除然后画一个新的,但是旧的被留下.一个很好的例子:

var SavedCircles = [];
var circleInfo = function()
{
  this.x = 0;
  this.y = 0;
  this.startX = 0;
  this.startY = 0;
  this.radius = 0;
}
circle = {};

function draw()
{
   for(var x=0;x<SavedCircles.length;x++)
   {
       ctx.beginPath();
       ctx.arc(SavedCircles[x].X, SavedCircles[x].Y, SavedCircles[x].radius, 0, 2.0 * Math.PI);
       ctx.stroke();
   }
}

function mouseDown()
{
  circle = new circleInfo();
}

function mouseUp()
{
   SavedCircles.push(circle);
}

function mouseMove()
{
   draw();
}

因此,您可以摆脱保存和恢复,也更快地清除画布简单地通过:canvas.width = canvas.width;
这将帮助你保存所有画过的圆。2用你的代码填充剩下的部分。

相关问题