HTMLMesh.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. import {
  2. CanvasTexture,
  3. LinearFilter,
  4. Mesh,
  5. MeshBasicMaterial,
  6. PlaneGeometry,
  7. sRGBEncoding,
  8. Color
  9. } from 'three';
  10. class HTMLMesh extends Mesh {
  11. constructor( dom ) {
  12. const texture = new HTMLTexture( dom );
  13. const geometry = new PlaneGeometry( texture.image.width * 0.001, texture.image.height * 0.001 );
  14. const material = new MeshBasicMaterial( { map: texture, toneMapped: false, transparent: true } );
  15. super( geometry, material );
  16. function onEvent( event ) {
  17. material.map.dispatchDOMEvent( event );
  18. }
  19. this.addEventListener( 'mousedown', onEvent );
  20. this.addEventListener( 'mousemove', onEvent );
  21. this.addEventListener( 'mouseup', onEvent );
  22. this.addEventListener( 'click', onEvent );
  23. this.dispose = function () {
  24. geometry.dispose();
  25. material.dispose();
  26. material.map.dispose();
  27. canvases.delete( dom );
  28. this.removeEventListener( 'mousedown', onEvent );
  29. this.removeEventListener( 'mousemove', onEvent );
  30. this.removeEventListener( 'mouseup', onEvent );
  31. this.removeEventListener( 'click', onEvent );
  32. };
  33. }
  34. }
  35. class HTMLTexture extends CanvasTexture {
  36. constructor( dom ) {
  37. super( html2canvas( dom ) );
  38. this.dom = dom;
  39. this.anisotropy = 16;
  40. this.encoding = sRGBEncoding;
  41. this.minFilter = LinearFilter;
  42. this.magFilter = LinearFilter;
  43. // Create an observer on the DOM, and run html2canvas update in the next loop
  44. const observer = new MutationObserver( () => {
  45. if ( ! this.scheduleUpdate ) {
  46. // ideally should use xr.requestAnimationFrame, here setTimeout to avoid passing the renderer
  47. this.scheduleUpdate = setTimeout( () => this.update(), 16 );
  48. }
  49. } );
  50. const config = { attributes: true, childList: true, subtree: true, characterData: true };
  51. observer.observe( dom, config );
  52. this.observer = observer;
  53. }
  54. dispatchDOMEvent( event ) {
  55. if ( event.data ) {
  56. htmlevent( this.dom, event.type, event.data.x, event.data.y );
  57. }
  58. }
  59. update() {
  60. this.image = html2canvas( this.dom );
  61. this.needsUpdate = true;
  62. this.scheduleUpdate = null;
  63. }
  64. dispose() {
  65. if ( this.observer ) {
  66. this.observer.disconnect();
  67. }
  68. this.scheduleUpdate = clearTimeout( this.scheduleUpdate );
  69. super.dispose();
  70. }
  71. }
  72. //
  73. const canvases = new WeakMap();
  74. function html2canvas( element ) {
  75. const range = document.createRange();
  76. const color = new Color();
  77. function Clipper( context ) {
  78. const clips = [];
  79. let isClipping = false;
  80. function doClip() {
  81. if ( isClipping ) {
  82. isClipping = false;
  83. context.restore();
  84. }
  85. if ( clips.length === 0 ) return;
  86. let minX = - Infinity, minY = - Infinity;
  87. let maxX = Infinity, maxY = Infinity;
  88. for ( let i = 0; i < clips.length; i ++ ) {
  89. const clip = clips[ i ];
  90. minX = Math.max( minX, clip.x );
  91. minY = Math.max( minY, clip.y );
  92. maxX = Math.min( maxX, clip.x + clip.width );
  93. maxY = Math.min( maxY, clip.y + clip.height );
  94. }
  95. context.save();
  96. context.beginPath();
  97. context.rect( minX, minY, maxX - minX, maxY - minY );
  98. context.clip();
  99. isClipping = true;
  100. }
  101. return {
  102. add: function ( clip ) {
  103. clips.push( clip );
  104. doClip();
  105. },
  106. remove: function () {
  107. clips.pop();
  108. doClip();
  109. }
  110. };
  111. }
  112. function drawText( style, x, y, string ) {
  113. if ( string !== '' ) {
  114. if ( style.textTransform === 'uppercase' ) {
  115. string = string.toUpperCase();
  116. }
  117. context.font = style.fontWeight + ' ' + style.fontSize + ' ' + style.fontFamily;
  118. context.textBaseline = 'top';
  119. context.fillStyle = style.color;
  120. context.fillText( string, x, y + parseFloat( style.fontSize ) * 0.1 );
  121. }
  122. }
  123. function buildRectPath( x, y, w, h, r ) {
  124. if ( w < 2 * r ) r = w / 2;
  125. if ( h < 2 * r ) r = h / 2;
  126. context.beginPath();
  127. context.moveTo( x + r, y );
  128. context.arcTo( x + w, y, x + w, y + h, r );
  129. context.arcTo( x + w, y + h, x, y + h, r );
  130. context.arcTo( x, y + h, x, y, r );
  131. context.arcTo( x, y, x + w, y, r );
  132. context.closePath();
  133. }
  134. function drawBorder( style, which, x, y, width, height ) {
  135. const borderWidth = style[ which + 'Width' ];
  136. const borderStyle = style[ which + 'Style' ];
  137. const borderColor = style[ which + 'Color' ];
  138. if ( borderWidth !== '0px' && borderStyle !== 'none' && borderColor !== 'transparent' && borderColor !== 'rgba(0, 0, 0, 0)' ) {
  139. context.strokeStyle = borderColor;
  140. context.lineWidth = parseFloat( borderWidth );
  141. context.beginPath();
  142. context.moveTo( x, y );
  143. context.lineTo( x + width, y + height );
  144. context.stroke();
  145. }
  146. }
  147. function drawElement( element, style ) {
  148. let x = 0, y = 0, width = 0, height = 0;
  149. if ( element.nodeType === Node.TEXT_NODE ) {
  150. // text
  151. range.selectNode( element );
  152. const rect = range.getBoundingClientRect();
  153. x = rect.left - offset.left - 0.5;
  154. y = rect.top - offset.top - 0.5;
  155. width = rect.width;
  156. height = rect.height;
  157. drawText( style, x, y, element.nodeValue.trim() );
  158. } else if ( element.nodeType === Node.COMMENT_NODE ) {
  159. return;
  160. } else if ( element instanceof HTMLCanvasElement ) {
  161. // Canvas element
  162. if ( element.style.display === 'none' ) return;
  163. context.save();
  164. const dpr = window.devicePixelRatio;
  165. context.scale( 1 / dpr, 1 / dpr );
  166. context.drawImage( element, 0, 0 );
  167. context.restore();
  168. } else {
  169. if ( element.style.display === 'none' ) return;
  170. const rect = element.getBoundingClientRect();
  171. x = rect.left - offset.left - 0.5;
  172. y = rect.top - offset.top - 0.5;
  173. width = rect.width;
  174. height = rect.height;
  175. style = window.getComputedStyle( element );
  176. // Get the border of the element used for fill and border
  177. buildRectPath( x, y, width, height, parseFloat( style.borderRadius ) );
  178. const backgroundColor = style.backgroundColor;
  179. if ( backgroundColor !== 'transparent' && backgroundColor !== 'rgba(0, 0, 0, 0)' ) {
  180. context.fillStyle = backgroundColor;
  181. context.fill();
  182. }
  183. // If all the borders match then stroke the round rectangle
  184. const borders = [ 'borderTop', 'borderLeft', 'borderBottom', 'borderRight' ];
  185. let match = true;
  186. let prevBorder = null;
  187. for ( const border of borders ) {
  188. if ( prevBorder !== null ) {
  189. match = ( style[ border + 'Width' ] === style[ prevBorder + 'Width' ] ) &&
  190. ( style[ border + 'Color' ] === style[ prevBorder + 'Color' ] ) &&
  191. ( style[ border + 'Style' ] === style[ prevBorder + 'Style' ] );
  192. }
  193. if ( match === false ) break;
  194. prevBorder = border;
  195. }
  196. if ( match === true ) {
  197. // They all match so stroke the rectangle from before allows for border-radius
  198. const width = parseFloat( style.borderTopWidth );
  199. if ( style.borderTopWidth !== '0px' && style.borderTopStyle !== 'none' && style.borderTopColor !== 'transparent' && style.borderTopColor !== 'rgba(0, 0, 0, 0)' ) {
  200. context.strokeStyle = style.borderTopColor;
  201. context.lineWidth = width;
  202. context.stroke();
  203. }
  204. } else {
  205. // Otherwise draw individual borders
  206. drawBorder( style, 'borderTop', x, y, width, 0 );
  207. drawBorder( style, 'borderLeft', x, y, 0, height );
  208. drawBorder( style, 'borderBottom', x, y + height, width, 0 );
  209. drawBorder( style, 'borderRight', x + width, y, 0, height );
  210. }
  211. if ( element instanceof HTMLInputElement ) {
  212. let accentColor = style.accentColor;
  213. if ( accentColor === undefined || accentColor === 'auto' ) accentColor = style.color;
  214. color.set( accentColor );
  215. const luminance = Math.sqrt( 0.299 * ( color.r ** 2 ) + 0.587 * ( color.g ** 2 ) + 0.114 * ( color.b ** 2 ) );
  216. const accentTextColor = luminance < 0.5 ? 'white' : '#111111';
  217. if ( element.type === 'radio' ) {
  218. buildRectPath( x, y, width, height, height );
  219. context.fillStyle = 'white';
  220. context.strokeStyle = accentColor;
  221. context.lineWidth = 1;
  222. context.fill();
  223. context.stroke();
  224. if ( element.checked ) {
  225. buildRectPath( x + 2, y + 2, width - 4, height - 4, height );
  226. context.fillStyle = accentColor;
  227. context.strokeStyle = accentTextColor;
  228. context.lineWidth = 2;
  229. context.fill();
  230. context.stroke();
  231. }
  232. }
  233. if ( element.type === 'checkbox' ) {
  234. buildRectPath( x, y, width, height, 2 );
  235. context.fillStyle = element.checked ? accentColor : 'white';
  236. context.strokeStyle = element.checked ? accentTextColor : accentColor;
  237. context.lineWidth = 1;
  238. context.stroke();
  239. context.fill();
  240. if ( element.checked ) {
  241. const currentTextAlign = context.textAlign;
  242. context.textAlign = 'center';
  243. const properties = {
  244. color: accentTextColor,
  245. fontFamily: style.fontFamily,
  246. fontSize: height + 'px',
  247. fontWeight: 'bold'
  248. };
  249. drawText( properties, x + ( width / 2 ), y, '✔' );
  250. context.textAlign = currentTextAlign;
  251. }
  252. }
  253. if ( element.type === 'range' ) {
  254. const [ min, max, value ] = [ 'min', 'max', 'value' ].map( property => parseFloat( element[ property ] ) );
  255. const position = ( ( value - min ) / ( max - min ) ) * ( width - height );
  256. buildRectPath( x, y + ( height / 4 ), width, height / 2, height / 4 );
  257. context.fillStyle = accentTextColor;
  258. context.strokeStyle = accentColor;
  259. context.lineWidth = 1;
  260. context.fill();
  261. context.stroke();
  262. buildRectPath( x, y + ( height / 4 ), position + ( height / 2 ), height / 2, height / 4 );
  263. context.fillStyle = accentColor;
  264. context.fill();
  265. buildRectPath( x + position, y, height, height, height / 2 );
  266. context.fillStyle = accentColor;
  267. context.fill();
  268. }
  269. if ( element.type === 'color' || element.type === 'text' || element.type === 'number' ) {
  270. clipper.add( { x: x, y: y, width: width, height: height } );
  271. drawText( style, x + parseInt( style.paddingLeft ), y + parseInt( style.paddingTop ), element.value );
  272. clipper.remove();
  273. }
  274. }
  275. }
  276. /*
  277. // debug
  278. context.strokeStyle = '#' + Math.random().toString( 16 ).slice( - 3 );
  279. context.strokeRect( x - 0.5, y - 0.5, width + 1, height + 1 );
  280. */
  281. const isClipping = style.overflow === 'auto' || style.overflow === 'hidden';
  282. if ( isClipping ) clipper.add( { x: x, y: y, width: width, height: height } );
  283. for ( let i = 0; i < element.childNodes.length; i ++ ) {
  284. drawElement( element.childNodes[ i ], style );
  285. }
  286. if ( isClipping ) clipper.remove();
  287. }
  288. const offset = element.getBoundingClientRect();
  289. let canvas = canvases.get( element );
  290. if ( canvas === undefined ) {
  291. canvas = document.createElement( 'canvas' );
  292. canvas.width = offset.width;
  293. canvas.height = offset.height;
  294. canvases.set( element, canvas );
  295. }
  296. const context = canvas.getContext( '2d'/*, { alpha: false }*/ );
  297. const clipper = new Clipper( context );
  298. // console.time( 'drawElement' );
  299. drawElement( element );
  300. // console.timeEnd( 'drawElement' );
  301. return canvas;
  302. }
  303. function htmlevent( element, event, x, y ) {
  304. const mouseEventInit = {
  305. clientX: ( x * element.offsetWidth ) + element.offsetLeft,
  306. clientY: ( y * element.offsetHeight ) + element.offsetTop,
  307. view: element.ownerDocument.defaultView
  308. };
  309. window.dispatchEvent( new MouseEvent( event, mouseEventInit ) );
  310. const rect = element.getBoundingClientRect();
  311. x = x * rect.width + rect.left;
  312. y = y * rect.height + rect.top;
  313. function traverse( element ) {
  314. if ( element.nodeType !== Node.TEXT_NODE && element.nodeType !== Node.COMMENT_NODE ) {
  315. const rect = element.getBoundingClientRect();
  316. if ( x > rect.left && x < rect.right && y > rect.top && y < rect.bottom ) {
  317. element.dispatchEvent( new MouseEvent( event, mouseEventInit ) );
  318. if ( element instanceof HTMLInputElement && element.type === 'range' && ( event === 'mousedown' || event === 'click' ) ) {
  319. const [ min, max ] = [ 'min', 'max' ].map( property => parseFloat( element[ property ] ) );
  320. const width = rect.width;
  321. const offsetX = x - rect.x;
  322. const proportion = offsetX / width;
  323. element.value = min + ( max - min ) * proportion;
  324. element.dispatchEvent( new InputEvent( 'input', { bubbles: true } ) );
  325. }
  326. }
  327. for ( let i = 0; i < element.childNodes.length; i ++ ) {
  328. traverse( element.childNodes[ i ] );
  329. }
  330. }
  331. }
  332. traverse( element );
  333. }
  334. export { HTMLMesh };