0

I'm sorry if this is one of those questions that fundamentally mistakes how React is supposed to work, but I've hit a wall.

I'm building a Rails app using React that is trying to create an HTMLCanvas element, draw a picture onto that canvas, and then update with user input to put text on the image.

class Image extends React.Component {

componentDidMount(){
    this.updateCanvas();
}

updateCanvas(){
// var imageObj = new Image();
// imageObj.src = './app/assets/image.jpg'

<Image ref='imageObj' source={{uri: '/assets/image.jpg'}} style={{width: 40, height: 40}} />

    var ctx = this.refs.canvas.getContext('2d');

    ctx.drawImage(this.refs.imageObj, 0, 0);
}

render() {
    return (
        <canvas ref='canvas' width={867} height={600}/>
    );
}
}

I've included commented-out code to show other things I've unsuccessfully tried.

And my HTML is:

<%= react_component('Image') %>

When I run this, I get:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

Based on this answer, I suspect the issue has to do with the ImageObj.src not being the correct path, not being of the right property, etc., but I'm not sure how to go about it.

Thanks for any help on this!

Community
  • 1
  • 1
  • Your custom `Image` component is not returning a DOM node for image. Try `ReactDOM.findDOMNode(this.refs.imageObj)` (and don't forget to `import ReactDOM from 'react-dom'`) – Gosha A Jul 06 '16 at 21:21

1 Answers1

0

I figured out the answer to do what I want to do. All of the issues and reasons why things were breaking is more of a novel than a post, but I wanted to put up my current solution just incase anybody has any similar issues in the future.

HTML:

<%= react_component('myCanvasComponent') %>

myCanvasComponent.js.jsx.erb:

var myCanvasComponent = React.createClass({

componentDidMount: function(){

var draw = function(){
    ctx.drawImage(objectImg, 100, 100);
}

var can = this.refs.canvas;
var ctx = can.getContext('2d');

var objectImg = new Image();
var imgPath = "<%= image_path('image.jpg') %>";
objectImg.src = imgPath

objectImg.onload = function(){
    draw();
}

},

render: function() {
    return (
        <canvas ref='canvas' width={867} height={600}/>
    );
}
})

I'm sure this isn't perfect and suggestions are still welcome for best practices, but works.