使用 JS 在 Canvas 内设置图像大小

Setting Image Size inside Canvas with JS

大家好,
于是就有了HTMLCanvas带图片编辑的工具。看起来像这样 -

<div class="col-md-12 col-lg-8 col-sm-12" id="mainDiv">
  <div 
    id="canvas1Div" 
    data-toggle="tooltip" 
    title="" 
    data-original-title="Image Processing Area"
  >
    <canvas id="canvas1" width="564" height="488"> </canvas>
  </div>
  <div
    id="canvasDiv" 
    data-toggle="tooltip" 
    data-original-title="" 
    title="" 
    style="border: 0px;"
  >
    <canvas id="canvas3" width="188" height="240"> </canvas>
    <canvas
      id="canvas4" 
      width="188" 
      height="240" 
      style="width: 188px; height: 240px;"
    > </canvas>
  </div>
</div>

那么有没有可能 JavaScript 通过在浏览器?
谢谢。

尝试使用此方法在 canvas 上添加图像:

ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
  • sx, sy, sWidth & sHeight 用于裁剪图像
  • dxdydWidthdHeight 用于在 canvas 中定位图像。这些参数应该与您想要的矩形位置和大小相关。

要了解有关此结帐的更多信息,请查看此 link:CanvasRenderingContext2D.drawImage()

编辑

使用本机 Image class 从您的电脑导入任何图像:

const image = new Image(width, height);

// render image on canvas when it‘s done loading
image.onload = () => ctx.drawImage(image, …);

// load the image
image.src = './path/to/image.png';