UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

116 lines (92 loc) 2.81 kB
/** @jsx jsx */ import {jsx} from '@instructure/emotion' import {Component} from 'react' import PropTypes from 'prop-types' import '../../common/ellipsePolyfill' import Canvas from '../../common/Canvas' import canvasPropTypes, {pickProps, defaultProps} from '../../common/Canvas/propTypes' import generateComponentTheme from './theme' import generateStyle from './styles' import {withStyleOverrides} from '@instructure/quiz-common/util/withStyleOverrides' @withStyleOverrides(generateStyle, generateComponentTheme) export default class Target extends Component { static displayName = 'Target' static componentId = `Quizzes${this.displayName}` static propTypes = {...canvasPropTypes, ...{styles: PropTypes.object}} static defaultProps = defaultProps __getCoordinates(e) { const x = e.nativeEvent.offsetX const y = e.nativeEvent.offsetY return [{x, y}] } __drawEllipse(radiusX, radiusY, centerX, centerY) { const ctx = this.canvas.canvasElement.getContext('2d') this.canvas.setStrokeStyle() ctx.globalAlpha = 1 ctx.lineWidth = 4 ctx.beginPath() ctx.ellipse(centerX, centerY, Math.abs(radiusX), Math.abs(radiusY), 0, 0, 2 * Math.PI) ctx.closePath() ctx.shadowColor = this.props.styles.shadowColor ctx.shadowBlur = 1 ctx.shadowOffsetX = 0 ctx.shadowOffsetY = 0 ctx.stroke() // render border } canvasRef = node => { this.canvas = node } drawShape = (coordinates = []) => { if (coordinates.length === 1) { const internalGap = 2 const pointA = { x: coordinates[0].x - internalGap, y: coordinates[0].y - internalGap, } const pointB = { x: coordinates[0].x + internalGap, y: coordinates[0].y + internalGap, } const radiusX = (pointB.x - pointA.x) * 0.5 const radiusY = (pointB.y - pointA.y) * 0.5 const centerX = pointA.x + radiusX const centerY = pointA.y + radiusY const externalGap = 10 this.__drawEllipse( // internal circle radiusX, radiusY, centerX, centerY, ) this.__drawEllipse( // external circle radiusX + externalGap, radiusY + externalGap, centerX, centerY, ) } } // =========== // ACTIONS // =========== onMouseUp = e => { const coordinates = this.__getCoordinates(e) this.canvas.drawShape(coordinates) this.canvas.stopDrawing(coordinates) } // override the default behaviour that's not needed for this type onMouseOut = () => {} render() { return ( <Canvas realRef={this.canvasRef} drawShape={this.drawShape} onMouseUp={this.onMouseUp} onMouseOut={this.onMouseOut} {...pickProps(this.props)} /> ) } }