当前位置: 首页 > 工具软件 > ZRender > 使用案例 >

canvas绘图创建文字,画圆等(zrender插件)

章翔宇
2023-12-01
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="shortcut icon" href="#" />
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <title>Hello, ZRender!</title>
</head>

<body>
    <div class="container">
        <div class="row">
            <div id="main" class="col-md-8 border">

            </div>
            <div class="col-md-3 offset-md-1">
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <strong>欢迎使用画图工具!</strong> 你可以在左边的画板上绘图。
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <button type="button" data-type="move" class="btn btn-outline-primary active">移动</button>
                <button type="button" data-type="circle" class="btn btn-outline-secondary">圆形</button>
                <!-- <button type="button" class="btn btn-outline-success">Success</button>
                <button type="button" class="btn btn-outline-danger">Danger</button>
                <button type="button" class="btn btn-outline-warning">Warning</button>
                <button type="button" class="btn btn-outline-info">Info</button>
                <button type="button" class="btn btn-outline-light">Light</button> -->
                <button type="button" data-type="text" class="btn btn-outline-dark">文字</button>

                <div class="input-group mb-1"></div>
                <div class="input-group mb-1">
                    <label for="basic-url">选择你喜欢的颜色:</label>
                    <input id="element-color" type="color">
                </div>

                <div class="input-group input-group-sm mb-1">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="inputGroup-sizing-sm">请设置合适的线宽:</span>
                    </div>
                    <input id="element-number" type="number" class="form-control" aria-label="Small"
                        aria-describedby="inputGroup-sizing-sm">
                </div>

                <div class="input-group mb-3" id="input-text" style="display: none; position: absolute;">
                    <input id="input-content" type="text" class="form-control" placeholder="请输入 文字"
                        aria-label="Recipient's username" aria-describedby="basic-addon2">
                    <div class="input-group-append">
                        <button id="yes" class="btn btn-outline-secondary" type="button">确定</button>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <script src="js/jquery.slim.min.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/zrender.js"></script>
    <script src="js/index.js"></script>
</body>

</html>
/** ---全局变量---*/

var zr;
// 设置当前操作类型为移动
var type = "move";
// 当前操作元素对象
var currentObj = null;
var position = {};

/** ------*/

$(function () {
    // 切换按钮选中样式
    $(".btn").click(function () {
        $(this).addClass('active');
        $(this).siblings().removeClass('active');
        // 修改当前操作类型
        if (typeof ($(this).attr("data-type")) != "undefined") {
            type = $(this).attr("data-type");
        }
        isMove(type);
    });
    // 初始化zrender
    zr = zrender.init(document.getElementById('main'));
    $('#main').mousedown(function (e) {
        // console.log('canvas鼠标按下事件');
        let element = {};
        let shape = {};
        let style = {};
        position.x = e.offsetX;
        position.y = e.offsetY;
        switch (type) {
            case 'circle':
                // console.log('创建圆形');
                shape.cx = position.x;
                shape.cy = position.y;
                shape.r = 0;
                style.fill = "rgba(255,255,255,0)";
                style.stroke = "#ff0000";
                element.shape = shape;
                element.style = style;
                let circle = new zrender.Circle(element);
                circle.on('click', function () {
                    // console.log('点击获取颜色');
                    $("#element-color").val(style.stroke);
                    $('#element-number').val(this.style.lineWidth);
                    currentObj = this;
                    // zr.addHover(this);
                    // 创建动画
                    // this.animate('style', true)
                    //     .when(500, { opacity: 0 })
                    //     .when(1000, { opacity: 1 })
                    //     .done(function () {
                    //         // Animation done
                    //     })
                    //     .start()
                }).on('mousewheel', function (ev) {
                    var e = (ev || event).wheelDelta * 3;
                    this.attr('shape', this.shape.r += e);
                    zr.refresh();
                });
                currentObj = circle;
                zr.add(circle);
                break;
            case 'text':
                // console.log('创建文字');
                guidance(position);
                break;

            default:
                break;
        }
    });
    $('#main').mousemove(function (e) {
        // console.log('canvas鼠标移动事件');
        if (currentObj == null) {
            return;
        }
        switch (type) {
            case 'circle':
                // console.log('创建圆形');
                currentObj.attr('shape', { r: Math.sqrt(Math.pow(currentObj.shape.cx - e.offsetX, 2) + Math.pow(currentObj.shape.cy - e.offsetY, 2)) });
                break;

            default:
                break;
        }
    });
    $('#main').mouseup(function () {
        if (type == "move") return;
        currentObj = null;
    });
    // 监听颜色选择器的颜色改变事件
    $('#element-color').change(function () {
        if(typeof(currentObj.__proto__) == "null") return;
        if (currentObj.__proto__.type == "text") currentObj.attr('style', { textFill: this.value });
        if (currentObj.__proto__.type == "circle") currentObj.attr('style', { stroke: this.value });

    });
    // 监听线宽输入框的改变事件
    $('#element-number').change(function () {
        if (currentObj.__proto__.type == "circle") currentObj.attr('style', { lineWidth: this.value });

    });
    // 监听确定按钮事件
    $('#yes').click(function () {
        // 删除当前闪烁的line
        if (preLine) zr.remove(preLine);
        // 创建文字
        let text = new zrender.Text({
            style: {
                x: position.x,
                y: position.y,
                textFill: '#ff0000',
                text: $('#input-content').val()
            }
        }).on('click', function () {
            $('#element-color').val(this.style.textFill);
            currentObj = this;
        }).on('mousewheel', function (ev) {
            var e = (ev || event).wheelDelta * 1;
            this.attr('shape', this.style.fontSize += e);
            zr.refresh();
        });
        currentObj = text;
        zr.add(text);
        $('#input-text').hide();
        $('#input-content').val("");
    });
});

// 根据类型设置元素是否可以移动
function isMove(type) {
    if (type == "move") {
        for (let i of zr.storage._displayList) {
            i.draggable = true;
        }
    } else {
        for (let i of zr.storage._displayList) {
            i.draggable = false;
        }
        currentObj = null;
    }
}
// 创建文字引导标志
var preLine;
function guidance(position) {
    // 在画板上点击时要删除上一个创建的闪烁line
    if (preLine) zr.remove(preLine);
    let line = new zrender.Line({
        style: {
            stroke: "rgba(0,0,0,1)",
            fill: "#000",
            lineWidth: 2
        },
        shape: {
            x1: position.x,
            y1: position.y,
            x2: position.x,
            y2: position.y + 20
        }
    });
    line.animate('style', true).when(500, { opacity: 1 }).when(1000, { opacity: 0 }).start();
    preLine = line;
    zr.add(line);
    let pos = document.getElementById('main').getBoundingClientRect();
    $('#input-text').show().offset({ top: pos.top + position.y + 40, left: pos.left + position.x - 100 });
}

将引入 Bootstrap 样式表的 <link> 标签复制并粘贴到 <head> 中,并放在所有其他样式表之前。

<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 

Bootstrap 中的许多组件需要依赖 JavaScript 才能运行。具体来说,他们依赖的是 jQueryPopper.js 以及我们自己开发的 JavaScript 插件。具体操作就是将下列 <script> 标签放到页面底部的 </body> 标签之前。注意顺序,jQuery 必须放在最前面,然后是 Popper.js,最后是我们自己的 JavaScript 插件。

我们使用的是 jQuery’s slim build(即,瘦身版) 版本,也同时支持完整版本。

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

zrender下载地址

https://github.com/ecomfe/zrender 

 类似资料: