【问题标题】:Using multiple arcs to crop circle from image使用多条弧线从图像中裁剪圆圈
【发布时间】:2018-06-02 17:14:02
【问题描述】:

我正在尝试从 2 张图像中裁剪出一个圆圈并将它们并排放置,如下所示:

const ctx = $('#canvas')[0].getContext("2d");

const image = new Image();
image.onload = () => {
        const coords = [[115, 62.5], [495, 62.5]];
        const coords2 = [[65, 12.5] , [445, 12.5]];

        for(let i = 0; i < coords.length; i++) {
            ctx.beginPath();
            ctx.arc(coords[i][0], coords[i][1], 50, 0, Math.PI * 2, true);
            ctx.clip();
            ctx.drawImage(image, coords2[i][0], coords2[i][1], 100, 100);

        }
    };
image.src = 'https://placeholdit.imgix.net/~text?txtsize=50&w=700&h=250&bg=afeafe';
#canvas {
    border:1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>

但是,这只是裁剪了一张图片,而另一张没有显示,我不明白为什么?

当我注释掉这些行时

ctx.beginPath();
ctx.arc(coords[i][0], coords[i][1], 50, 0, Math.PI * 2, true);
ctx.clip();

它正确放置了 2 个图像,因此定位不是问题。

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:

    通过在剪切之前保存上下文,然后在剪切后恢复它,如下所示:

    const ctx = $('#canvas')[0].getContext("2d");
    
    const image = new Image();
    
    image.onload = () => {
    	const coords = [[115, 62.5], [495, 62.5]];
    	const coords2 = [[65, 12.5] , [445, 12.5]]
    	for(let i = 0; i < coords.length; i++) {
    	    ctx.save();
    	    ctx.beginPath();
    	    ctx.arc(coords[i][0], coords[i][1], 50, 0, Math.PI * 2, true);
      	    ctx.closePath();
      	    ctx.clip();
      	    ctx.drawImage(image, coords2[i][0], coords2[i][1], 100, 100);
      	    ctx.restore();
    	}
    };
    
    image.src = 'https://placeholdit.imgix.net/~text?txtsize=50&w=700&h=250&bg=afeafe';
    #canvas {
        border:1px solid grey;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <canvas id="canvas" width="800" height="200"></canvas>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 2020-04-16
      • 2013-01-14
      • 2016-01-24
      • 2012-06-20
      • 1970-01-01
      • 2015-09-22
      相关资源
      最近更新 更多