【问题标题】:How can I add an image inside a circle in canvas?如何在画布的圆圈内添加图像?
【发布时间】:2017-08-03 09:11:20
【问题描述】:

我想插入这张图片

var img=new Image();
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/desert1.jpg";

进入我正在用这个函数绘制的圆圈

function drawBall() {
    //ctx.globalCompositeOperation='destination-in';
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.drawImage(img,10,20);
    ctx.globalCompositeOperation='source-over';
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

这是画布当前的样子:

【问题讨论】:

标签: javascript html5-canvas


【解决方案1】:

globalCompositeOperation 模式source-over 是默认的 gCO 模式,它会在现有模式的基础上绘制新内容。
您需要将其设置为destination-in您在画布上绘制了一些东西之后,因此只有新像素和已绘制的像素会重叠的像素才会保留。

var img=new Image();
img.onload = drawBall;
img.src="https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg";

function drawBall() {
    var ctx = c.getContext('2d');
    c.width = this.width;
    c.height = this.height;
  
    // default gCO is source-over
    ctx.drawImage(img,-250,-200, img.width*.7, img.height*.7);
    // now we change the gCO
    ctx.globalCompositeOperation='destination-in';
    ctx.beginPath();
    ctx.arc(75, 75, 50, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    // reset to default
    ctx.globalCompositeOperation='source-over';
    // closePath is useless here
    //ctx.closePath();
}
<canvas id="c"></canvas>

【讨论】:

  • 对不起,我没有展示整个代码,无论如何这运行完美,但有一个问题我想让图像四处移动。在 arc(x,y...) 中,我正在改变 x 和 y,这很好,但现在只有背景在改变。
  • @Cotne 您还需要更改传递给drawImage的 x 和 y 值
猜你喜欢
  • 2013-12-03
  • 2013-09-06
  • 2019-06-24
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 2012-11-12
相关资源
最近更新 更多