HTMLMesh.js 12 KB

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