0

好吧,我环顾四周,找到了一个代码,它可以让我成功地在画布上绘制一个圆圈,并将该圆圈用作我的图像的蒙版。

代码如下所示:(对于我不知道的真正创建者来说是 codus)

var ctx = document.getElementById('your_canvas').getContext("2d");

ctx.arc(100,100, 50, 0, Math.PI*2,true); // you can use any shape
ctx.clip();

var img = new Image();
img.addEventListener('load', function(e) {
    ctx.drawImage(this, 0, 0, 200, 300);
}, true);
img.src="/path/to/image.jpg";

假设我想要 5 个不同的圆圈,所有圆圈都有不同的图像,并且每个圆圈的位置都不同。

有人知道 id 是怎么做的吗?

4

2 回答 2

1

是的,和马特说的差不多……

这是代码和小提琴:http: //jsfiddle.net/m1erickson/Vu2Fm/

您可以通过使用图像预加载器在画布上绘制之前加载所有 5 个图像来改进此代码。

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var img1=new Image();
    img1.onload=function(){

        var img2=new Image();
        img2.onload=function(){

            // draw a clipping circle and then an image to clip
            ctx.save();
            ctx.beginPath();
            ctx.strokeStyle="blue";
            ctx.arc(100, 100, 50, 0 , 2 * Math.PI, false);
            ctx.stroke();
            ctx.clip();
            ctx.beginPath();
            ctx.arc(100, 100, 50, 0 , 2 * Math.PI, false);
            ctx.drawImage(img1,10,0);
            ctx.restore();

            // draw a second clipping circle and then an image to clip
            ctx.save();
            ctx.beginPath();
            ctx.strokeStyle="green";
            ctx.arc(275, 100, 75, 0 , 2 * Math.PI, false);
            ctx.stroke();
            ctx.clip();
            ctx.beginPath();
            ctx.drawImage(img2,150,0);
            ctx.restore();

        }
        img2.src="http://dl.dropbox.com/u/139992952/coffee.png";
    }
    img1.src="http://dl.dropbox.com/u/139992952/house%20vector.png";

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=400 height=250></canvas>
</body>
</html>
于 2013-03-15T02:15:23.703 回答
1

为了保持代码简短,请创建一个函数,其中包含将在图像之间更改的设置的参数。

可重复使用的功能:

function drawImageCircle(ctx, circleX, circleY, radius,
                              imageX, imageY, imageWidth, imageHeight, imageUrl) {

    var img = new Image();
    img.onload = function(){
        ctx.save();
        ctx.beginPath();
        ctx.arc(circleX, circleY, radius, 0, Math.PI*2, true);
        ctx.clip();
        ctx.drawImage(this, imageX, imageY, imageWidth, imageHeight);
        ctx.restore();
    };
    img.src = imageUrl;
}

var ctx = document.getElementById('your_canvas').getContext("2d");

drawImageCircle(ctx, 100,100, 50,  0,0,     200,300, 'image1.jpg');
drawImageCircle(ctx, 400,400, 50,  300,300, 200,300, 'image2.jpg');

多次执行此操作时,使用save()and很重要。restore()

于 2013-03-15T02:25:09.863 回答