Canvas绘制图片和区域

如何使用Canvas在图片上绘制区域?
一. 首先,我们需要初始化三个canvas画布(初始化Canvas)

 

initCanvas() {
  // 初始化canvas画布
  let canvasWrap = document.getElementsByClassName("canvas-wrap");
  this.wrapWidth = canvasWrap[0].clientWidth;
  this.wrapHeight = canvasWrap[0].clientHeight;
 
  this.imgCanvas = document.getElementById("imgCanvas");
  this.imgCtx = this.imgCanvas.getContext("2d");
 
  // 绘制canvas
  this.drawCanvas = document.getElementById("drawCanvas");
  this.drawCtx = this.drawCanvas.getContext("2d");
 
  // 保存绘制区域 saveCanvas
  this.saveCanvas = document.getElementById("saveCanvas");
  this.saveCtx = this.saveCanvas.getContext("2d");
}
  1. imgCanvas用于绘制原始图片
  2. drawCanvas用于临时绘制区域
  3. saveCanvas用于保存最终绘制的区域
二. 计算并设置canvas的宽高比例,以适应图片尺寸
initImgCanvas() {
  // 计算宽高比
  let ww = this.wrapWidth; // 画布宽度
  let wh = this.wrapHeight; // 画布高度 
  let iw = this.imgWidth; // 图片宽度
  let ih = this.imgHeight; // 图片高度
 
  if (iw / ih < ww / wh) {
    // 以高为主
    this.ratio = ih / wh;
    this.canvasHeight = wh;
    this.canvasWidth = (wh * iw) / ih;
  } else {
    // 以宽为主 
    this.ratio = iw / ww;
    this.canvasWidth = ww;
    this.canvasHeight = (ww * ih) / iw;
  }
 
  // 初始化画布大小
  this.imgCanvas.width = this.canvasWidth;
  this.imgCanvas.height = this.canvasHeight;
  this.drawCanvas.width = this.canvasWidth; 
  this.drawCanvas.height = this.canvasHeight;
  this.saveCanvas.width = this.canvasWidth;
  this.saveCanvas.height = this.canvasHeight;
 
  // 图片加载绘制
  let img = document.createElement("img");
  img.src = this.imgUrl;
  img.onload = () => {
    console.log("图片已加载");
    this.imgCtx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight);
    this.renderDatas(); // 渲染原有数据
  };
}

这里先计算画布和图片的宽高比,根据比例关系决定以宽为主还是以高为主进行等比缩放。然后设置三个canvas的宽高,并在图片加载完成后将其绘制到imgCanvas上。renderDatas函数用于渲染已有的绘制数据。

三. 绘制的主要逻辑 

startDraw() {
  // 绘制区域
  if (this.isDrawing) return;
  this.isDrawing = true;
  // 绘制逻辑
  this.drawCanvas.addEventListener("click", this.drawImageClickFn);
  this.drawCanvas.addEventListener("dblclick", this.drawImageDblClickFn);
  this.drawCanvas.addEventListener("mousemove", this.drawImageMoveFn);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值