由点做的对象有图象背景

时间:2015-09-01 23:16:17

标签: javascript html css canvas

我想达到如下图所示的结果。基本上,具有背景图像并且用n个点掩蔽的对象。我想最好的方法是使用js canvas,以及哪些函数/库最适合使用?

enter image description here

1 个答案:

答案 0 :(得分:1)

enter image description here

Html5具有内置裁剪功能,可用于效果。

  1. 定义画布路径。
  2. 致电context.clip()
  3. 任何新图纸只会出现在路径定义的剪裁区域内。
  4. 示例代码和演示:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    var points=[];
    points.push({x:261,y:41});
    points.push({x:300,y:122});
    points.push({x:288,y:223});
    points.push({x:150,y:261});
    points.push({x:36,y:139});
    points.push({x:55,y:81});
    
    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg";
    function start(){
      canvas.width=img.width;
      canvas.height=img.height;
      clipBackground(points);
    }
    
    function clipBackground(points){
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(points[0].x,points[0].y);
      for(var i=1;i<points.length;i++){
        var p=points[i];
        ctx.lineTo(p.x,p.y);
      }
      ctx.clip();
      ctx.drawImage(img,0,0);
      ctx.restore();
    }
    body{ background-color: ivory; }
    #canvas{border:1px solid red; margin:0 auto; }
    <h4>Background clipped on canvas</h4>
    <canvas id="canvas" width=300 height=300></canvas>
    <h4>Original image</h4>
    <img src='https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg'>