说在前面
- 测试浏览器:Microsoft Edge(PC版本 97.0.1072.55)
- github库:AR.js
- AR系列文章:这里
- go版本:go version go1.17.3 windows/amd64
- three.js版本:r79(版本比较老)
- 其他:
AR.js 支持three.js 。
效果图
代码
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script src='/js/three.js'></script>
<script src="/js/ar.js"></script>
<script>THREEx.ArToolkitContext.baseURL = '../'</script>
<body style='margin : 0px; overflow: hidden; font-family: Monospace;'>
<div style='position: absolute; top: 10px; width:100%; text-align: center; z-index: 1;'>
</div>
<script>
var renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
renderer.setSize(640, 480);
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild(renderer.domElement);
var onRenderFcts = [];
var scene = new THREE.Scene();
var camera = new THREE.Camera();
scene.add(camera);
var arToolkitSource = new THREEx.ArToolkitSource({
sourceType: 'webcam',
})
arToolkitSource.init(function onReady() {
setTimeout(() => {
onResize()
}, 2000);
})
window.addEventListener('resize', function () {
onResize()
})
function onResize() {
arToolkitSource.onResizeElement()
arToolkitSource.copyElementSizeTo(renderer.domElement)
if (arToolkitContext.arController !== null) {
arToolkitSource.copyElementSizeTo(arToolkitContext.arController.canvas)
}
}
var arToolkitContext = new THREEx.ArToolkitContext({
cameraParametersUrl: THREEx.ArToolkitContext.baseURL + '/assets/camera_para.dat',
detectionMode: 'mono',
})
arToolkitContext.init(function onCompleted() {
camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix());
})
onRenderFcts.push(function () {
if (arToolkitSource.ready === false) return
arToolkitContext.update(arToolkitSource.domElement)
scene.visible = camera.visible
})
var markerControls = new THREEx.ArMarkerControls(arToolkitContext, camera, {
type: 'pattern',
patternUrl: THREEx.ArToolkitContext.baseURL + '/assets/patt.hiro',
changeMatrixMode: 'cameraTransformMatrix'
})
scene.visible = false
var geometry = new THREE.CubeGeometry(1, 1, 1);
var material = new THREE.MeshNormalMaterial({
transparent: true,
opacity: 0.5,
side: THREE.DoubleSide
});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.y = geometry.parameters.height / 2
scene.add(mesh);
onRenderFcts.push(function () {
renderer.render(scene, camera);
})
var lastTimeMsec = null
requestAnimationFrame(function animate(nowMsec) {
requestAnimationFrame(animate);
lastTimeMsec = lastTimeMsec || nowMsec - 1000 / 60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
onRenderFcts.forEach(function (onRenderFct) {
onRenderFct(deltaMsec / 1000, nowMsec / 1000)
})
})
</script>
</body>
|