【问题标题】:How to fill shapes with image in p5.js and matter.js如何在 p5.js 和 matter.js 中用图像填充形状
【发布时间】:2021-05-28 13:28:12
【问题描述】:

我正在尝试使用 p5.js 和 matter.js

var Engine = Matter.Engine,
            World = Matter.World,
            Body = Matter.Body,
            Events = Matter.Events,
            Bodies = Matter.Bodies;
        var engine;
        var world;
        var box1;
        var boxes = [];

        var ground;

        var img;

        function setup() {
            createCanvas(window.innerWidth, window.innerHeight);
            engine = Engine.create();
            world = engine.world;
            Engine.run(engine);
            ground = new Boundary(window.innerWidth /2, window.innerHeight, window.innerWidth, 10);
            World.add(world, ground);
            img = loadImage("https://i.ibb.co/jZccXfR/image.png");
        }

            

        function mouseDragged() {
            boxes.push(new Ball(mouseX, mouseY, 20))
        }
        function mousePressed() {
            boxes.push(new Ball(mouseX, mouseY, 20))
        }

        function draw() {
            background(51);

            for(var i = 0; i < boxes.length; i++){
                boxes[i].show();
                img.mask(boxes[i]);
            }
            ground.show();
        }

这是我写的代码。 (在绘图中没有遮罩功能,它工作正常)
当我运行此代码时,出现错误“srcImage.loadPixels 不是函数”。 如何用图像填充形状?

【问题讨论】:

    标签: p5.js matter.js


    【解决方案1】:

    您可能需要先将图像加载移动到preload()(有关详细信息,请参阅loadImage() reference):

    function preload(){
       img = loadImage("https://i.ibb.co/jZccXfR/image.png");
    }
    

    不清楚boxes[i] 是什么,但希望它们是p5.Image(或p5.Graphics)实例,否则您将无法将它们用作掩码。

    目前看起来您正在对同一图像应用蒙版:每个 mask() 调用都会覆盖之前的调用,因此它只是最后一个将用作蒙版的框。或者,您可以使用 p5.Graphics 实例使用 box[i] x, y, w, h 属性在黑色背景上绘制白色框。

    一旦img 被加载,您可以制作一个可以重复使用的副本,如果您想“重置”回原始图像,如果多次对原始图像应用蒙版最终会完全侵蚀图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多