在HTML5画布上动态添加文本

时间:2019-01-25 07:10:18

标签: javascript html css html5 canvas

我正在创建一个基本的光栅图形编辑器应用程序(刚刚启动),但无法在画布上动态添加文本。

该应用有2个分区。左侧是工具箱,右侧是编辑器画布。

用户将从左侧选择一个工具(添加文本按钮),然后在画布上单击任意位置以添加文本(为什么子画布位于父画布中?我希望主画布具有用于文本形状的多个画布)图片等,因为单个画布无法容纳多个上下文。

HTML:

<div class="app">
    <aside class="app__tools">
        <button class="btn tools__btn tools__text">Add Text</button>
    </aside>

    <canvas class="app__drawing-board">

    </canvas>
</div>

选择工具箱JavaScript(效果很好):

// TOOLBOX
const buttons = document.querySelectorAll('.tools__btn');

let button_selected = false;

for (let i=0; i<buttons.length; i++) {
    buttons[i].addEventListener('click', e => {
        console.log('BUTTON: clicked');
        console.log('button selected', button_selected);

        const attributes = e.target.getAttribute('class').split(' ');
        const selected = attributes.filter(className => className === 'selected').length === 0;

        console.log('selected', selected);
        button_selected = selected;

        if (selected) attributes.push('selected');
        else attributes.splice(-1, 1);

        e.target.setAttribute('class', attributes.join(' '));
    });
}

选择工具按钮时将鼠标悬停在画布上(效果很好):

// CANVAS 
const canvas = document.getElementsByClassName('app__drawing-board')[0];

canvas.addEventListener('mouseover', e => {
    console.log('CANVAS: mouseover');
    console.log('button selected', button_selected);

    e.target.style.cursor = button_selected? 'text' : 'auto';
});

向画布添加文本(此处失败):

canvas.addEventListener('click', e => {
    if (button_selected) {
        console.log('CANVAS: clicked');
        console.log(e);

        const text_canvas = document.createElement('canvas');
        const context = text_canvas.getContext('2d');

        text_canvas.class = 'drawing-board__text';

        context.font = '40pt Calibri';
        context.fillText('Hello World', e.pageX, e.pageY);

        canvas.appendChild(text_canvas);
        console.log(context);
    }
});

点击画布后,我的结果是:

<canvas class="app__drawing-board">
    <canvas>
    "

            "
    </canvas>
</canvas>

尽管如此,上下文打印:

CanvasRenderingContext2D {canvas: canvas, globalAlpha: 1, globalCompositeOperation: "source-over", filter: "none", imageSmoothingEnabled: true, …}

Codepen:https://codepen.io/danyal-imran/pen/WPQmvy

0 个答案:

没有答案