使用three.js 实现一个 马赛克得 shader

使用three.js 实现一个 马赛克得 shader
在这里插入图片描述

源链接:https://threehub.cn/#/codeMirror?navigation=ThreeJS&classify=shader&id=mosaicShader

国内站点预览:http://threehub.cn

github地址: https://github.com/z2586300277/three-cesium-examples

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import * as dat from 'dat.gui'

const box = document.getElementById('box')

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(75, box.clientWidth / box.clientHeight, 0.1, 1000)

camera.position.set(0, 0, 1)

const renderer = new THREE.WebGLRenderer()

renderer.setSize(box.clientWidth, box.clientHeight)

box.appendChild(renderer.domElement)

new OrbitControls(camera, renderer.domElement)

animate()

function animate() {

    requestAnimationFrame(animate)

    renderer.render(scene, camera)

}

window.onresize = () => {

    renderer.setSize(box.clientWidth, box.clientHeight)

    camera.aspect = box.clientWidth / box.clientHeight

    camera.updateProjectionMatrix()

}

const vertexShader = ` 
    varying vec2 vUv;
    void main(){
    vUv = uv;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}`

const fragmentShader = `
    varying vec2 vUv;
    uniform sampler2D tDiffuse;
    uniform vec2 vScreenSize;
    uniform float fMosaicScale;
    void main() {
    vec2 vUv2 = vUv;
    vUv2.x = floor(vUv2.x * vScreenSize.x / fMosaicScale) / (vScreenSize.x / fMosaicScale) + (fMosaicScale / 2.0) / vScreenSize.x;
    vUv2.y = floor(vUv2.y * vScreenSize.y / fMosaicScale) / (vScreenSize.y / fMosaicScale) + (fMosaicScale / 2.0) / vScreenSize.y;

    vec4 color = texture2D(tDiffuse, vUv2);
    gl_FragColor = color;
}`

const uniforms = {

    tDiffuse: { type: 't', value: new THREE.TextureLoader().load(`https://threehub.cn/` + 'files/author/z2586300277.png') },

    vScreenSize: { type: "v2", value: new THREE.Vector2(window.innerWidth, window.innerHeight) },

    fMosaicScale: { type: "f", value: 20.0 },

}

const material = new THREE.ShaderMaterial({ uniforms, vertexShader, fragmentShader });

const geometry = new THREE.PlaneGeometry();

const mesh = new THREE.Mesh(geometry, material);

scene.add(mesh);

var gui = new dat.GUI();
gui.add(uniforms['fMosaicScale'], 'value', 1.0, 100.0).step(1.0).name('mosaicScale');

/**
 * 名称: 马赛克
 * 作者: 优雅永不过时 https://github.com/z2586300277
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值