How to add image to polygon in fabric js?

时光怂恿深爱的人放手 提交于 2020-07-08 02:08:31

问题


1I am creating a polygon with definite points,when i try to add an image to the polygon object.Image is not rendering in the polygon.it is rendering from starting point of the canvas. Below is the code i used.Please tell me where i am doing wrong. Appreciate any help!Thanks

Jsfiddle Link https://jsfiddle.net/u3bfscom/6/ Add Points and create polygon later add Texture.

        fabric.Image.fromURL('https://image.freepik.com/free-photo/roof-texture_21206171.jpg', function (oImg)  {
        for(var i=0;canvas.getObjects().length>i;i++)
        {
            if(canvas.getObjects()[i].name=="Polygon")
            {   
                    canvas.getObjects()[i].set(oImg);
            }
        }
        canvas.renderAll();
        });

回答1:


Got the Answer.

fabric.Image.fromURL('https://image.freepik.com/free-photo/roof-texture_21206171.jpg', function (img)  {
            var patternSourceCanvas = new fabric.StaticCanvas();
            patternSourceCanvas.add(img);
            var pattern = new fabric.Pattern({
              source: function() {
                patternSourceCanvas.setDimensions({
                  width: img.getWidth(),
                  height: img.getHeight()
                });
                return patternSourceCanvas.getElement();
              },
            });
            console.log(img);
           for(var i=0;canvas.getObjects().length>i;i++)
            {
                if(canvas.getObjects()[i].name=="Polygon")
                {   
                        canvas.getObjects()[i].set("fill", pattern);
                        canvas.renderAll();
                }
            }
        });


来源:https://stackoverflow.com/questions/37177529/how-to-add-image-to-polygon-in-fabric-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!