HTMLMesh.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import {
  2. CanvasTexture,
  3. LinearFilter,
  4. Mesh,
  5. MeshBasicMaterial,
  6. PlaneGeometry,
  7. SRGBColorSpace,
  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.colorSpace = SRGBColorSpace;
  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. // Do not render invisible elements, comments and scripts.
  149. if ( element.nodeType === Node.COMMENT_NODE || element.nodeName === 'SCRIPT' || ( element.style && element.style.display === 'none' ) ) {
  150. return;
  151. }
  152. let x = 0, y = 0, width = 0, height = 0;
  153. if ( element.nodeType === Node.TEXT_NODE ) {
  154. // text
  155. range.selectNode( element );
  156. const rect = range.getBoundingClientRect();
  157. x = rect.left - offset.left - 0.5;
  158. y = rect.top - offset.top - 0.5;
  159. width = rect.width;
  160. height = rect.height;
  161. drawText( style, x, y, element.nodeValue.trim() );
  162. } else if ( element instanceof HTMLCanvasElement ) {
  163. // Canvas element
  164. const rect = element.getBoundingClientRect();
  165. x = rect.left - offset.left - 0.5;
  166. y = rect.top - offset.top - 0.5;
  167. context.save();
  168. const dpr = window.devicePixelRatio;
  169. context.scale( 1 / dpr, 1 / dpr );
  170. context.drawImage( element, x, y );
  171. context.restore();
  172. } else if ( element instanceof HTMLImageElement ) {
  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. context.drawImage( element, x, y, width, height );
  179. } else {
  180. const rect = element.getBoundingClientRect();
  181. x = rect.left - offset.left - 0.5;
  182. y = rect.top - offset.top - 0.5;
  183. width = rect.width;
  184. height = rect.height;
  185. style = window.getComputedStyle( element );
  186. // Get the border of the element used for fill and border
  187. buildRectPath( x, y, width, height, parseFloat( style.borderRadius ) );
  188. const backgroundColor = style.backgroundColor;
  189. if ( backgroundColor !== 'transparent' && backgroundColor !== 'rgba(0, 0, 0, 0)' ) {
  190. context.fillStyle = backgroundColor;
  191. context.fill();
  192. }
  193. // If all the borders match then stroke the round rectangle
  194. const borders = [ 'borderTop', 'borderLeft', 'borderBottom', 'borderRight' ];
  195. let match = true;
  196. let prevBorder = null;
  197. for ( const border of borders ) {
  198. if ( prevBorder !== null ) {
  199. match = ( style[ border + 'Width' ] === style[ prevBorder + 'Width' ] ) &&
  200. ( style[ border + 'Color' ] === style[ prevBorder + 'Color' ] ) &&
  201. ( style[ border + 'Style' ] === style[ prevBorder + 'Style' ] );
  202. }
  203. if ( match === false ) break;
  204. prevBorder = border;
  205. }
  206. if ( match === true ) {
  207. // They all match so stroke the rectangle from before allows for border-radius
  208. const width = parseFloat( style.borderTopWidth );
  209. if ( style.borderTopWidth !== '0px' && style.borderTopStyle !== 'none' && style.borderTopColor !== 'transparent' && style.borderTopColor !== 'rgba(0, 0, 0, 0)' ) {
  210. context.strokeStyle = style.borderTopColor;
  211. context.lineWidth = width;
  212. context.stroke();
  213. }
  214. } else {
  215. // Otherwise draw individual borders
  216. drawBorder( style, 'borderTop', x, y, width, 0 );
  217. drawBorder( style, 'borderLeft', x, y, 0, height );
  218. drawBorder( style, 'borderBottom', x, y + height, width, 0 );
  219. drawBorder( style, 'borderRight', x + width, y, 0, height );
  220. }
  221. if ( element instanceof HTMLInputElement ) {
  222. let accentColor = style.accentColor;
  223. if ( accentColor === undefined || accentColor === 'auto' ) accentColor = style.color;
  224. color.set( accentColor );
  225. const luminance = Math.sqrt( 0.299 * ( color.r ** 2 ) + 0.587 * ( color.g ** 2 ) + 0.114 * ( color.b ** 2 ) );
  226. const accentTextColor = luminance < 0.5 ? 'white' : '#111111';
  227. if ( element.type === 'radio' ) {
  228. buildRectPath( x, y, width, height, height );
  229. context.fillStyle = 'white';
  230. context.strokeStyle = accentColor;
  231. context.lineWidth = 1;
  232. context.fill();
  233. context.stroke();
  234. if ( element.checked ) {
  235. buildRectPath( x + 2, y + 2, width - 4, height - 4, height );
  236. context.fillStyle = accentColor;
  237. context.strokeStyle = accentTextColor;
  238. context.lineWidth = 2;
  239. context.fill();
  240. context.stroke();
  241. }
  242. }
  243. if ( element.type === 'checkbox' ) {
  244. buildRectPath( x, y, width, height, 2 );
  245. context.fillStyle = element.checked ? accentColor : 'white';
  246. context.strokeStyle = element.checked ? accentTextColor : accentColor;
  247. context.lineWidth = 1;
  248. context.stroke();
  249. context.fill();
  250. if ( element.checked ) {
  251. const currentTextAlign = context.textAlign;
  252. context.textAlign = 'center';
  253. const properties = {
  254. color: accentTextColor,
  255. fontFamily: style.fontFamily,
  256. fontSize: height + 'px',
  257. fontWeight: 'bold'
  258. };
  259. drawText( properties, x + ( width / 2 ), y, '✔' );
  260. context.textAlign = currentTextAlign;
  261. }
  262. }
  263. if ( element.type === 'range' ) {
  264. const [ min, max, value ] = [ 'min', 'max', 'value' ].map( property => parseFloat( element[ property ] ) );
  265. const position = ( ( value - min ) / ( max - min ) ) * ( width - height );
  266. buildRectPath( x, y + ( height / 4 ), width, height / 2, height / 4 );
  267. context.fillStyle = accentTextColor;
  268. context.strokeStyle = accentColor;
  269. context.lineWidth = 1;
  270. context.fill();
  271. context.stroke();
  272. buildRectPath( x, y + ( height / 4 ), position + ( height / 2 ), height / 2, height / 4 );
  273. context.fillStyle = accentColor;
  274. context.fill();
  275. buildRectPath( x + position, y, height, height, height / 2 );
  276. context.fillStyle = accentColor;
  277. context.fill();
  278. }
  279. if ( element.type === 'color' || element.type === 'text' || element.type === 'number' ) {
  280. clipper.add( { x: x, y: y, width: width, height: height } );
  281. drawText( style, x + parseInt( style.paddingLeft ), y + parseInt( style.paddingTop ), element.value );
  282. clipper.remove();
  283. }
  284. }
  285. }
  286. /*
  287. // debug
  288. context.strokeStyle = '#' + Math.random().toString( 16 ).slice( - 3 );
  289. context.strokeRect( x - 0.5, y - 0.5, width + 1, height + 1 );
  290. */
  291. const isClipping = style.overflow === 'auto' || style.overflow === 'hidden';
  292. if ( isClipping ) clipper.add( { x: x, y: y, width: width, height: height } );
  293. for ( let i = 0; i < element.childNodes.length; i ++ ) {
  294. drawElement( element.childNodes[ i ], style );
  295. }
  296. if ( isClipping ) clipper.remove();
  297. }
  298. const offset = element.getBoundingClientRect();
  299. let canvas = canvases.get( element );
  300. if ( canvas === undefined ) {
  301. canvas = document.createElement( 'canvas' );
  302. canvas.width = offset.width;
  303. canvas.height = offset.height;
  304. canvases.set( element, canvas );
  305. }
  306. const context = canvas.getContext( '2d'/*, { alpha: false }*/ );
  307. const clipper = new Clipper( context );
  308. // console.time( 'drawElement' );
  309. context.clearRect( 0, 0, canvas.width, canvas.height );
  310. drawElement( element );
  311. // console.timeEnd( 'drawElement' );
  312. return canvas;
  313. }
  314. function htmlevent( element, event, x, y ) {
  315. const mouseEventInit = {
  316. clientX: ( x * element.offsetWidth ) + element.offsetLeft,
  317. clientY: ( y * element.offsetHeight ) + element.offsetTop,
  318. view: element.ownerDocument.defaultView
  319. };
  320. window.dispatchEvent( new MouseEvent( event, mouseEventInit ) );
  321. const rect = element.getBoundingClientRect();
  322. x = x * rect.width + rect.left;
  323. y = y * rect.height + rect.top;
  324. function traverse( element ) {
  325. if ( element.nodeType !== Node.TEXT_NODE && element.nodeType !== Node.COMMENT_NODE ) {
  326. const rect = element.getBoundingClientRect();
  327. if ( x > rect.left && x < rect.right && y > rect.top && y < rect.bottom ) {
  328. element.dispatchEvent( new MouseEvent( event, mouseEventInit ) );
  329. if ( element instanceof HTMLInputElement && element.type === 'range' && ( event === 'mousedown' || event === 'click' ) ) {
  330. const [ min, max ] = [ 'min', 'max' ].map( property => parseFloat( element[ property ] ) );
  331. const width = rect.width;
  332. const offsetX = x - rect.x;
  333. const proportion = offsetX / width;
  334. element.value = min + ( max - min ) * proportion;
  335. element.dispatchEvent( new InputEvent( 'input', { bubbles: true } ) );
  336. }
  337. }
  338. for ( let i = 0; i < element.childNodes.length; i ++ ) {
  339. traverse( element.childNodes[ i ] );
  340. }
  341. }
  342. }
  343. traverse( element );
  344. }
  345. export { HTMLMesh };