如何在React.js的Heart形状内的画布上渲染大量图像?

时间:2020-04-30 11:22:35

标签: reactjs

我试图在React.js中制作一个心形的照片马赛克,我想输出如下内容:

enter image description here

我在下面尝试这种方式,但是其编码过多。获得相似输出的最佳方法是什么?

import React from 'react';

    class Canvas extends React.Component {

      componentDidMount() {
        this.updateCanvas();
      }

      updateCanvas() {
        const ctx = this.refs.canvas.getContext('2d');

        var imageObj1 = [];

        imageObj1[0] = new Image();
        imageObj1[0].src = 'https://somelink/1.jpg';

        imageObj1[1] = new Image();
        imageObj1[1].src = 'https://somelink/2.jpg';


                imageObj1[0].onload = function() {

                    ctx.drawImage(imageObj1[0], 375, 154, 50, 50);
                }

                imageObj1[1].onload = function() {

                    ctx.drawImage(imageObj1[1], 350, 104, 50, 50);
                }

                ctx.rect(400, 104, 50, 50);

                ctx.rect(450, 60, 50, 50);

//                .
//                .
//                .

//              And So on.. I have to give position manually

                ctx.rect(350, 670, 50, 50);

                ctx.rect(400, 670, 50, 50);

                ctx.rect(375, 720, 50, 50);
                ctx.stroke();
    }

    render() {

        return(
          <div>
            <canvas ref="canvas" align="center" width="800" height="800"></canvas>
          </div>
        )
      }
    }
    export default Canvas

我也尝试了css方式,但是它的输出不是我想要的,因为图像仅以400x400正方形呈现。

.heart {
  background-color: #ccc;
  display: inline-block;
  height: 400px;
  margin: 0 10px;
  position: relative;
  top: 300px;
  left: 275px;
  transform: rotate(-45deg);
  width: 400px;

}

.heart:before,
.heart:after {
  content: "";
  background-color: #ccc;
  border-radius: 50%;
  height: 400px;
  position: absolute;
  width: 400px;
  z-index: -1;
}

.heart:before {
  top: -200px;
  left: 0;
}

.heart:after {
  left: 200px;
  top: 0;
}

将此.heart className应用于div中,这给了我这个结果。

enter image description here

如何执行此操作?我被困住了。请帮帮我吗?

0 个答案:

没有答案
相关问题