【问题标题】:how to round an image in matter.js如何在matter.js中对图像进行四舍五入
【发布时间】:2022-06-10 21:46:28
【问题描述】:

当球体掉落时,我想将图像放入其中,但它不适用于 fillStyle 渲染我只能着色,现在使用精灵我可以但它们不适合圆形,除非图像是圆形的,怎么可能我用 javascript 和 matter.js 将图像四舍五入

代码:

return Matter.Bodies.circle(280, 40, 11, {
    restitution: 0.5,
    render: {
        // fillStyle: '#F00',
        // strokeStyle: 'black',
        // lineWidth: 3,
        sprite: {
            texture: img,
            xScale: 0.3,
            yScale: 0.3,  
        }
    }
    
});

img从ticktok获取方形图片,我不知道怎么做圆形

【问题讨论】:

  • 您错过了问题最后一行的翻译。
  • 您还需要帮助吗,还是问题解决了?

标签: javascript matter.js


【解决方案1】:

我不确定 100%,如果这是最好的方法(对于您的用例),但您可以:

  • 创建一个助手canvas 元素:
    <canvas id='helper-canvas'></canvas>let canvas = document.createElement('canvas');

  • 设置画布的宽度/高度(宽度=所需的纹理宽度)

    ...
    canvas.width='100';
    canvas.height='100';
    ...
    
  • 将图像绘制到canvas 元素上(使用context)。

    ...
    ctx.drawImage(img, 0, 0); // "img" is a HtmlImageElement
    ...
    
  • 设置 composite-mode 并绘制一个应具有所需大小的圆

    ...
    ctx.globalCompositeOperation='destination-in';
    ctx.beginPath();
    ctx.arc(img.width/2,img.width/2,img.width/2,0,Math.PI*2);
    ctx.closePath();
    ctx.fill();
    ...
    
  • 生成新的url “创建图片”

    ...
    let imgUrl = img.toDataURL('image/png'); 
    ...
    

简单地创建 matter-body,用那个新图像:

Matter.Bodies.circle(280, 40, 11, {
    restitution: 0.5,
    render: {
        sprite: {
            texture: imgUrl,
            xScale: 0.3,
            yScale: 0.3,  
        }
    }      
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多