画布中的多个图层与React

时间:2017-12-30 13:34:01

标签: canvas

我尝试使用画布,这样我可以在图像上移动一个矩形,但我不知道如何使用两个图层来实现这一目标?我已经看到可以使用z-index,但这似乎不适用于react。问题是,图像和移动矩形彼此相邻,而不是彼此重叠。我怎样才能让这些图层相互叠加?

import React from 'react'
import ReactDOM from 'react-dom'
import './../css/index.css'

var img;
var ctx;
var ctx2;
var canvas;
var canvas2;
var color;
var coordinates;

var rectSize = {
  color: '#666',
  dim: { w: 20, h: 20 },
};

class App extends React.Component {


   constructor(props){
      super(props)

      window.a = this.state
   }

   componentDidMount(){
      this.SetImage();
   }


   SetImage() {
    img = new Image();
    img.crossOrigin = "Anonymous";
    img.src = testImgPath;
    canvas = this.canvas1;
    canvas2 = this.canvas2;
    ctx = canvas.getContext('2d');
    ctx2 = canvas2.getContext('2d');
    img.onload = function() {
      ctx.drawImage(img, 0, 0);
      img.style.display = 'none';
    };
    color = this.color1;
    coordinates = this.coordinates1;

    function pick(event) {
      var x = event.layerX;
      var y = event.layerY;
      var pixel = ctx.getImageData(x, y, 1, 1);
      var data = pixel.data;
      var rgba = 'rgba(' + data[0] + ', ' + data[1] +
                 ', ' + data[2] + ', ' + (data[3] / 255) + ')';
      var coord = '(x: ' +  x  + ', y: ' + y + ')';
      //color.style.background =  rgba;
      color.textContent = rgba;
      coordinates.textContent = coord;

      ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
      ctx2.fillStyle = 'red';
      ctx2.fillRect(x, y, rectSize.dim.w, rectSize.dim.h);
    }
    canvas.addEventListener('mousemove', pick);    
   }

   render(){
      return (
         <div className="main-container">            
            <div styles="position:relative">
              <canvas id="canvas1" ref={(ref) => this.canvas1 = ref} width="500" height="500" styles="z-index: 1; position:absolute; left:0px; top:0px;"/>
              <canvas id="canvas2" ref={(ref) => this.canvas2 = ref} width="500" height="500" styles="z-index: 2; position:absolute; left:0px; top:0px;"/>  
            </div>   

         </div>
      )
   }
}

ReactDOM.render(
   <App />,
   document.querySelector('#root')
)

1 个答案:

答案 0 :(得分:0)

              <canvas id="canvas1" ref={(ref) => this.canvas1 = ref} width="500" height="500" styles="z-index: 1; position:absolute; left:0px; top:0px;"/>

应该成为

          <canvas id="canvas1" ref={(ref) => this.canvas1 = ref} width="500" height="500" style={{zIndex:1, position: absolute, top: 0, left: 0}}/>