Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - fabric.js : How to make an image in the shape of a oval with strokes shadow etc?

I have been trying to show a image as oval shape but no luck.

below is my code snippet, which works for circle but there are gaps when we are converting image from rectangle to ellipse

how can i add both rx, ry in html canvas? this is how current code converts my rectangle image to ellipse, there are gaps in height & width they are not accurate.

sample output image:

enter image description here

fabric.util.loadImage(imageURL, function (img) {
      var oImg = new fabric.Image(img);


      if (slot.image_shape == "ellipse") {
        let shadow = (options && options.shadow) || {
          affectStroke: true,
        };
        const radius =
          oImg.width < oImg.height ? oImg.width / 2 : oImg.height / 2;
        oImg.set({
          clipTo: function (ctx) {
            return ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
          },
        });
      }
question from:https://stackoverflow.com/questions/65916009/fabric-js-how-to-make-an-image-in-the-shape-of-a-oval-with-strokes-shadow-etc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately I'm not aware of what fabric.js version you're actually using but from 2.4.0 onwards you can use the clipPath property. In conjunction with the Ellipse class you can directly use an ellipsoidal shape as a mask - which let's you directly enter values for rx and ry instead of just a radius.

Here's an example:

var canvas = window._canvas = new fabric.Canvas('canvas');

fabric.Image.fromURL('https://picsum.photos/200/200', function(img) {
  img.set({
    hasControls: false,
    hasBorders: false,
    left: 0,
    top: 0,
    clipPath: new fabric.Ellipse({
      rx: 100,
      ry: 50,
      originX: 'center',
      originY: 'center',
    }),
  });
  canvas.add(img);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.min.js"></script>
<canvas id="canvas" width="400" height="400" class="canvas"></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...