web3d-three.js场景设计器-sprite广告牌

  • three.js使用Sprite精灵实现文字或者图片广告牌
  • 1.将文字绘制到Canvas,调整对应宽高。
  • 2.作为Cavans材质绑定到Sprite
  • 3.加载到场景调整适当的scale

function createLabel({ text, fontSize, textColor, color, imageUrl }) {

    return new Promise((resolve, reject) => {

        let canvas = document.createElement('canvas');

        let context = canvas.getContext('2d');

        context.font = `${fontSize}px Arial`;

        let textWidth = context.measureText(text).width;

        canvas.width = Math.ceil(textWidth);

        canvas.height = Math.ceil(fontSize * 1.5);

        context.font = `${fontSize}px Arial`;

       

        if (color) {

            context.fillStyle = color;

            context.fillRect(0, 0, canvas.width, canvas.height);

        }

       

        let drawText = (imgHeight = 0) => {

            context.textBaseline = 'middle';

            context.textAlign = 'center';

            context.fillStyle = textColor;

            context.fillText(text, canvas.width / 2, (canvas.height + imgHeight) / 2);

            // context.fillText(text, canvas.width / 2, canvas.height - fontSize / 2);

         

            resolve(canvas);

        };

        if (imageUrl && imageUrl !== '') {

            let image = new Image();

            image.crossOrigin = "anonymous";

            image.onload = function() {

                let scale = textWidth / image.width;

                let imageHeight = image.height * scale;

                canvas.height += imageHeight;

                context.drawImage(image, 0, 0, image.width * scale, imageHeight);

                context.font = `${fontSize}px Arial`;

                drawText(imageHeight);

               

               

            };

            image.onerror = reject;

            image.src = imageUrl;

        } else {

            drawText();

        }

    });

}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-12 17:58:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-12 17:58:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-12 17:58:02       82 阅读
  4. Python语言-面向对象

    2024-01-12 17:58:02       91 阅读

热门阅读

  1. Jenkins相关问题及答案(2024)

    2024-01-12 17:58:02       45 阅读
  2. Docker快速安装MongoDB数据库

    2024-01-12 17:58:02       54 阅读
  3. 停止css @keyframes动画

    2024-01-12 17:58:02       58 阅读
  4. ubuntu 22.04源码装ros1 noetic

    2024-01-12 17:58:02       59 阅读
  5. 2024年Ubuntu18.04执行do-release-upgrade报错的解决方案

    2024-01-12 17:58:02       49 阅读
  6. 一个算法带来的反思+Map复杂方法的使用总结

    2024-01-12 17:58:02       38 阅读
  7. 深入了解线程

    2024-01-12 17:58:02       49 阅读
  8. Linux部署WBO在线白板

    2024-01-12 17:58:02       57 阅读
  9. 图像数据集扩展

    2024-01-12 17:58:02       59 阅读