HTMLMesh.js 12 KB

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