首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么ctx.strokeRect()的行为与顺序ctx.rect() ctx.stroke()调用不同

为什么ctx.strokeRect()的行为与顺序ctx.rect() ctx.stroke()调用不同
EN

Stack Overflow用户
提问于 2019-08-30 17:37:33
回答 1查看 292关注 0票数 0

我用创建-反应-应用程序创建了一个app应用程序。在这个应用程序中,用户上传一张画在画布上的图片。这个应用程序允许用户裁剪图像,当用户鼠标拖动图像时,我试图绘制裁剪区域的矩形预览。

下面是绘制动态作物区域预览的函数。这个功能很好,因为它使用的是ctx.strokeRect()。每次用户移动鼠标时,rectXY都会被更新,并调用drawCropRect来清除前一个矩形并创建一个新的矩形。

代码语言:javascript
复制
    // draw rectangle preview of cropped area
  const drawCropRect = (
    canvasRef,
    rectXY,
    croppedCanvasData
  ) => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(croppedCanvasData,0,0, 0,0,canvas.width,canvas.height);
    ctx.strokeStyle = "#f6dd43";
    // calling strokeRect() - this works
    ctx.strokeRect(
      rectXY.xStart,
      rectXY.yStart,
      rectXY.xCurrent - rectXY.xStart,
      rectXY.yCurrent - rectXY.yStart
    );
  };

  // calls drawCropRect when the user is dragging the mouse to crop image 

  useEffect(() => {
    if (props.step === "crop") {
      drawCropRect(canvasRef, cropRect, croppedCanvasData[0]);
    }
  }, [cropRect]);
  // cropRect is a state hook containing starting and current mouse positions
// drawCropRect will get called every time cropRect updates.. so whenever the user moves the mouse during a crop event. 

但是,如果没有调用ctx.strokeRect(),而是调用了ctx.rect(),然后调用了ctx.stroke(),则没有清除矩形,并且看到图像上生成的所有矩形。

这里有相同的函数,但是调用单独的ctx.rect()ctx.stroke()

代码语言:javascript
复制
  // draw rectangle preview of cropped area
  const drawCropRect = (canvasRef, rectXY, croppedCanvasData) => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(
      croppedCanvasData,
      0,
      0,
      0,
      0,
      canvas.width,
      canvas.height
    );
    ctx.strokeStyle = "#f6dd43";
    // calling rect() and then stroke()- this does not work
    ctx.rect(
      rectXY.xStart,
      rectXY.yStart,
      rectXY.xCurrent - rectXY.xStart,
      rectXY.yCurrent - rectXY.yStart
    );
    ctx.stroke();
  };

为什么会发生这种情况?当用户移动鼠标时,调用单独的ctx.rect()ctx.stroke()如何防止它们被清除?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-30 18:49:16

ctx.beginPath()rect()部分开始时尝试使用drawCropRect()

如果不使用ctx.beginPath(),它就会抛出画布。

希望这能有所帮助!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57731070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档