如何将图像放在圆形对象上?

时间:2016-12-13 12:41:28

标签: javascript php html css canvas

这是我用于画布游戏的圆圈变量。我如何在保持其在画布上的移动的同时将图像放在上面?

var img = new Image();
img.src = "img.png";   

var ball = {
    radius: 0
   ,position: { x: 0, y: 0 }
   ,velocity: { x: 0, y: 0 }
   ,acceleration: 0
   ,draw: 
     function() {
        context.fillStyle = "yellow";
        context.beginPath();
        context.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI); 
        context.fill();
      }  
}; 

1 个答案:

答案 0 :(得分:1)

最基本的方法是创建剪辑

   ,draw () {
        context.beginPath();
        context.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI); 
        context.save(); // save current state
        context.clip();
        context.drawImage(myImage,this.position.x-this.radius,this.position.y-this.radius,this.radius * 2,this.radius * 2);
        context.restore(); // removes the clip.
      } 

但这是一种缓慢的做法。最好是使用globalCompositeOperation创建一个掩码,以便屏蔽图像。此外,您应该在屏幕外的画布上绘制蒙版图像,这样您只需要进行一次蒙版,然后只需绘制屏幕外的画布..

相关问题