簡體   English   中英

如何在 canvas 中繪制圖像?

[英]How to draw behind an image in canvas?

我正在使用 canvas 進行圖片裁剪功能,但我不知道如何填充空白區域。

首先,這就是我正在做的事情:

Canvas 元件:

   <canvas
     id="previewCanvas"
     ref={previewCanvasRef}
     style={{
     border: '1px solid black',
     objectFit: 'contain',
     width: '300px',
     height: '300px',
     }}
  />

這是我用來繪制圖像的 function:

const TO_RADIANS = Math.PI / 180;

export async function canvasPreview(image, canvas, crop, scale = 1, rotate = 0) {
  const ctx = canvas.getContext('2d');

  if (!ctx) {
    throw new Error('No 2d context');
  }

  const scaleX = image.naturalWidth / image.width;
  const scaleY = image.naturalHeight / image.height;
  // devicePixelRatio slightly increases sharpness on retina devices
  // at the expense of slightly slower render times and needing to
  // size the image back down if you want to download/upload and be
  // true to the images natural size.
  const pixelRatio = window.devicePixelRatio;
  // const pixelRatio = 1

  canvas.width = Math.floor(crop.width * scaleX * pixelRatio);
  canvas.height = Math.floor(crop.height * scaleY * pixelRatio);

  ctx.scale(pixelRatio, pixelRatio);
  ctx.imageSmoothingQuality = 'high';

  const cropX = crop.x * scaleX;
  const cropY = crop.y * scaleY;

  const rotateRads = rotate * TO_RADIANS;
  const centerX = image.naturalWidth / 2;
  const centerY = image.naturalHeight / 2;

  ctx.save();

  // 5) Move the crop origin to the canvas origin (0,0)
  ctx.translate(-cropX, -cropY);
  // 4) Move the origin to the center of the original position
  ctx.translate(centerX, centerY);
  // 3) Rotate around the origin
  ctx.rotate(rotateRads);
  // 2) Scale the image
  ctx.scale(scale, scale);
  // 1) Move the center of the image to the origin (0,0)
  ctx.translate(-centerX, -centerY);
  ctx.drawImage(
    image,
    0,
    0,
    image.naturalWidth,
    image.naturalHeight,
    0,
    0,
    image.naturalWidth,
    image.naturalHeight
  );

  ctx.restore();
}

這就是我在瀏覽器上看到 canvas 的方式: 在此處輸入圖像描述

現在,當我將圖像轉換為 blob,然后轉換為文件 object 時,我得到如下圖像: 在此處輸入圖像描述

我期望發生的是得到這樣的圖像:(就像在預覽中一樣) 在此處輸入圖像描述

我究竟做錯了什么?

您可以點擊 StackOverflow 鏈接: https://stackoverflow.com/questions/15457619/html-canvas-drawing-grid-below-a-plot

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM