diff --git a/src/components/costume-canvas.js b/src/components/costume-canvas.js index f657e847d4b2d8423501625d5fa66f56ed31b15e..73c6002b6b6b82124f05ecf7daaf2a320476ddad 100644 --- a/src/components/costume-canvas.js +++ b/src/components/costume-canvas.js @@ -10,11 +10,6 @@ const xhr = require('xhr'); */ class CostumeCanvas extends React.Component { - render () { - return <canvas ref='costumeCanvas' - width={this.props.width} - height={this.props.height} />; - } componentDidMount () { this.load(); } @@ -30,20 +25,27 @@ class CostumeCanvas extends React.Component { } } draw () { + // Draw the costume to the rendered canvas. const img = this.img; const context = this.refs.costumeCanvas.getContext('2d'); // Scale to fit. let scale; + // Choose the larger dimension to scale by. if (img.width > img.height) { scale = this.refs.costumeCanvas.width / img.width; } else { scale = this.refs.costumeCanvas.height / img.height; } + // Rotate by the Scratch-value direction. const angle = (-90 + this.props.direction) * Math.PI / 180; + // Rotation origin point will be center of the canvas. const contextTranslateX = this.refs.costumeCanvas.width / 2; const contextTranslateY = this.refs.costumeCanvas.height / 2; + // First, clear the canvas. context.clearRect(0, 0, this.refs.costumeCanvas.width, this.refs.costumeCanvas.height); + // Translate the context to the center of the canvas, + // then rotate canvas drawing by `angle`. context.translate(contextTranslateX, contextTranslateY); context.rotate(angle); context.drawImage(img, @@ -51,6 +53,7 @@ class CostumeCanvas extends React.Component { -(scale * img.width / 2), -(scale * img.height / 2), scale * img.width, scale * img.height); + // Reset the canvas rotation and translation to 0, (0, 0). context.rotate(-angle); context.translate(-contextTranslateX, -contextTranslateY); } @@ -86,6 +89,11 @@ class CostumeCanvas extends React.Component { }; } } + render () { + return <canvas ref='costumeCanvas' + width={this.props.width} + height={this.props.height} />; + } } CostumeCanvas.defaultProps = {