javascript - 如何选择 Canvas 中的特定区域?

标签 javascript jquery html canvas

我是 Canvas 新手,我有一个图像 myimg.jpg,我已将此图像转换为 Canvas ,我正在尝试为脚跟应用一些图案图像。

我做不到。这是我的屏幕截图:

/image/7APVy.png

我怎样才能完成它。

<div id="myId">
  <canvas id="canvaswrapper" width="660" height="540"></canvas>
</div>
 function drawImage(){
    var ctx = $("canvas")[0].getContext("2d"),
        img = new Image();
    img.onload = function(){
      ctx.drawImage(img, 0, 0, 500, 500);
      ctx.beginPath();
      var img2= new Image();
      var w;
      var h;
      img2.src = "http://www.gravatar.com/avatar/e555bd971bc2f4910893cd5b785c30ff?s=128&d=identicon&r=PG";
      var pattern = ctx.createPattern(img2, "repeat");
      ctx.fillStyle = pattern;
      ctx.fillRect(0, 0, w, h);
      ctx.arc(300,305,50,0,2*Math.PI);
      ctx.fill();
      ctx.stroke();
   };
   img.src = "myimg.jpg"; 
 }
 drawImage();

最佳答案

您可以使用适合图像顶部的图像蒙版来定义要填充的区域 - 此步骤适用于 Photoshop/GIMP。

例如,保持鞋子原样:

shoe

为其创建一个 mask ,将愈合部分保留在原始位置(这样可以更轻松地将其拉回 - 您始终可以裁剪它并使用偏移量来绘制它)。 重要提示:背景必须是透明的:

mask

然后使用以下步骤叠加图案:

  1. 加载图案并将其定义为填充图案
  2. 蒙版绘制到空 Canvas 中
  3. 可选步骤:根据需要调整转换(平移、缩放)
  4. 选择复合模式“source-atop”
  5. 填充 Canvas
  6. 选择复合模式“destination-atop”
  7. 在顶部绘制主图像(将显示在蒙版/图案后面)
  8. 可选步骤:使用混合模式“乘法”绘制原始蒙版图像以添加阴影和高光(在 IE 中不起作用)。这将有助于创造深度错觉。对于 IE,可以选择使用减少的 Alpha 或仅包含阴影等的单独图像将其绘制在顶部

结果

result

示例

var iShoe = new Image, iMask = new Image, iPatt = new Image, count = 3;
iShoe.onload = iMask.onload = iPatt.onload = loader;
iShoe.src = "/image/hqL1C.png";
iMask.src = "/image/k5XWN.png";
iPatt.src = "/image/CEQ10.png";

function loader() {
  if (--count) return;  // wait until all images has loaded

  var ctx = document.querySelector("canvas").getContext("2d"),
      pattern = ctx.createPattern(iPatt, "repeat");

  // draw in mask
  ctx.drawImage(iMask, 0, 0);
  
  // change comp mode
  ctx.globalCompositeOperation = "source-atop";
  
  // fill mask
  ctx.scale(0.5, 0.5);                 // scale: 0.5
  ctx.fillStyle = pattern;             // remember to double the area to fill:
  ctx.fillRect(0, 0, ctx.canvas.width*2, ctx.canvas.height*2);
  ctx.setTransform(1,0,0,1,0,0);       // reset transform
  
  // draw shoe behind mask
  ctx.globalCompositeOperation = "destination-atop";
  ctx.drawImage(iShoe, 0, 0);
  
  // to make it more realistic, add mask in blend mode (does not work in IE):
  ctx.globalCompositeOperation = "multiply";
  if (ctx.globalCompositeOperation === "multiply") {
    ctx.drawImage(iMask, 0, 0);
  }
}
<canvas width=281 height=340></canvas>

关于javascript - 如何选择 Canvas 中的特定区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931736/

相关文章:

javascript - 如何在两个不同的 Angular 应用程序之间传递数据

javascript - 使用 HTML 修复轮播中的图像大小

javascript - 将表中的文本合并到 blob 中

javascript - 如何使用 ng-repeat 将 JSON 响应映射到 Html 页面

javascript - 删除 Canvas 元素的图像

JavaScript 执行返回函数的函数

javascript - npm install 返回 304 和 404 错误而不是安装包

javascript - 使用 javascript 更改数据属性

html - 如何将子 div 设置为父级的高度(100%)?

javascript - IE 如何处理无内容的 anchor 标记?