前言
在做threejs练手项目时,会存在同源策略的问题
倘若你需要从外部文件里载入几何体或是纹理贴图,由于浏览器same origin policy(同源策略)的安全限制,从本地文件系统载入外部文件将会失败,同时抛出安全性异常。
参照threejs的官方文档,给出两种解决方式
- 在浏览器中改变本地文件的安全策略,这将使你可以通过
- 搭建本地服务器
官方文档中也做了详细解析,还有开启本地服务器的几个例子;这里采用node的http-server
这里采取第二种解决方式
官方文档:
https://threejs.org/docs/index.html#manual/zh/introduction/Creating-a-scene
这里总结了一些资料:
https://blog.csdn.net/lzl980111/article/details/112652529
构建
使用到
npm
webpack
webpack.config.js
//导入path模块
const path=require('path')
const {
Plugin, BannerPlugin } = require('webpack')
// const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports={
//打包入口
entry:'./src/js/index.js',
//打包出口
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'dist')
},
//打包规则
module:{
rules:[
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
//插件配置
plugins:[
],
resolve:{
alias:{
'vue':'vue/dist/vue.js'
}
},
devServer:{
contentBase:"./dist",
inline:true
}
}
安装引入threejs
npm install three --save-dev
使用threejs
const THREE = require('three');
使用的时候需要将js打包
本地服务器
安装引入本地服务器
npm install http-server -g
开启服务器,在一个终端中调用:
http-server -p 8000