本文介绍了将多个文本实例添加到HTML5画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上找到这个代码,并一直在玩。它将文本添加到画布上的任何点。这是伟大的,但是当新文本被添加到画布上的上一个文本被删除。有多种实例的文本同时存在于画布上的简单方法吗?



我是JS的新手,在保存新文本后,无法在代码中看到删除文本的任何内容。我真的希望我不必保存所有的文本在一个数组以及x和y坐标,我不在那里附近熟练的足以做到这一点。



我使用的代码如下,但不会工作没有一些外部JS,所以这里是一个链接到工作版本,我复制它。



提前感谢任何建议

 <!DOCTYPE html> 
< html>
< head>
< link rel =stylesheettype =text / csshref =css / css.css>
< / head>
< body>
< div id =main>
< canvas id =c>< / canvas><! - canvas - >
< / div>
< script src =http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js>< / script>
< script type =text / javascriptsrc =text.js>< / script><! - Library to help text - >
< script type =text / javascript>
$('#c')。mousedown(function(e){
if($('#textAreaPopUp')。length == 0){
var mouseX = e.pageX - this.offsetLeft + $(#c)。position()。left;
var mouseY = e.pageY - this.offsetTop;

//将一个文本框在用户点击输入注释的画布中
var textArea =< div id ='textAreaPopUp'style ='position:absolute; top:+ mouseY +px; left:+ mouseX +px; z -index:30;'>< textarea id ='textareaTest'style ='width:100px; height:50px;'>< / textarea>;
var saveButton =&input; 'button'value ='save'id ='saveText'onclick ='saveTextFromArea(+ mouseY +,+ mouseX +);'>< / div>;
var appendString = textArea + saveButton;
$(#main)。append(appendString);
} else {
$('textarea#textareaTest')。remove();
$('#saveText ').remove();
// $('#textAreaPopUp')。remove();
var mouseX = e.pageX - this.offsetLeft + $(#c)。position()。left;
var mouseY = e.pageY - this.offsetTop;
//将文本区域框追加到用户在注释中输入的画布中
var textArea =< div id ='textAreaPopUp'style ='position:absolute; top:+ mouseY +px; left:+ mouseX +px; z-index:30;'>< textarea id ='textareaTest'style ='width:100px; height:50px;'>< / textarea&
var saveButton =< input type ='button'value ='save'id ='saveText'onclick ='saveTextFromArea(+ mouseY +,+ mouseX +);'>< / div> ;
var appendString = textArea + saveButton;
$(#main)。append(appendString);
}
});

函数saveTextFromArea(y,x){
//获取textarea的值然后销毁它和保存按钮
var text = $('textarea#textareaTest') .val();
$('textarea#textareaTest')。remove();
$('#saveText')。remove();
$('#textAreaPopUp')。remove();
//获取画布并添加文本函数
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var cw = canvas.clientWidth;
var ch = canvas.clientHeight;
canvas.width = cw;
canvas.height = ch;
//根据文本宽度100px将文本分成数组
var phraseArray = getLines(ctx,text,100);
//这将文本函数添加到ctx
CanvasTextFunctions.enable(ctx);
var counter = 0;
//设置字体样式
var font =sans;
var fontsize = 12;
ctx.strokeStyle =rgba(0,0,0,1);
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 0;
ctx.shadowColor =rgba(0,0,0,1);
//将每个短语绘制到屏幕,使顶部位置每次更多20px,所以它出现有换行符
$ .each(phraseArray,function(){
//设置布局中的位置
var lineheight = fontsize * 1.5;
var newline = ++ counter;
newline = newline * lineheight;
var topPlacement = y - $(#c ).position()。top + newline;
var leftPlacement = x - $(#c)。position()。left;
text = this;
// text
ctx.drawText(font,fontsize,leftPlacement,topPlacement,text);
ctx.save();
ctx.restore();
});
//重置投影,以便任何其他绘图没有它们
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 0;
ctx.shadowColor =rgba(0,0,0,0);
}

function getLines(ctx,phrase,maxPxLength){
//根据框宽度将文本区域文本划分为行
var wa = phrase .split(),
phraseArray = [],
lastPhrase =,
l = maxPxLength,
measure = 0;
ctx.font =16px sans-serif;
for(var i = 0; i var w = wa [i];
measure = ctx.measureText(lastPhrase + w).width;
if(measure< l){
lastPhrase + =(+ w);
} else {
phraseArray.push(lastPhrase);
lastPhrase = w;
}
if(i === wa.length-1){
phraseArray.push(lastPhrase);
break;
}
}
return phraseArray;
}
< / script>
< script src =js / text.js>< / script>
< script src =js / js.js>< / script>
< / body>
解决方案>

原因是每次都设置画布大小。发生这种情况时:



因此,首先要做的是预设大小在canvas元素上的元素标记(如下所示)或代码中的父范围中:

 < div id =main> 
&canvas; canvas id =cwidth = 500 height = 300>< / canvas> <! - 您想要的任何大小 - >
< / div>

然后从JavaScript中删除这些行:

  function saveTextFromArea(y,x){
...剪切例如...
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var cw = canvas.clientWidth;
var ch = canvas.clientHeight;
//canvas.width = cw; // remove this line
//canvas.height = ch; // remove this line

...削减了例如...


I found this code on the internet and have been playing around with it. It adds text to any point on a canvas. This is great however when new text is added to the canvas the previous text is deleted. Is there an easy way for multiple instances of text to exist on the canvas simultaneously?

I'm new to JS and can't see anything in the code that deletes the text once new text is saved. I'm really hoping that I won't have to save all the text in an array along with the x and y coordinates, I'm nowhere near skilled enough to do that.

The code I'm using is below, but wont work without some external JS, so here is a link to the working version I copied it from. http://oldstatic.travisberry.com/demos/canvas-text-demo/index.html

Thanks in advance for any suggestions

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/css.css">
</head>
<body>
    <div id="main">
        <canvas id="c"></canvas><!-- the canvas -->
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript" src="text.js"></script><!-- Library to help text -->
    <script type="text/javascript">
$('#c').mousedown(function(e){
            if ($('#textAreaPopUp').length == 0) {
                var mouseX = e.pageX - this.offsetLeft + $("#c").position().left;
                var mouseY = e.pageY - this.offsetTop;

                //append a text area box to the canvas where the user clicked to enter in a comment
                var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+mouseY+"px;left:"+mouseX+"px;z-index:30;'><textarea id='textareaTest' style='width:100px;height:50px;'></textarea>";
                var saveButton = "<input type='button' value='save' id='saveText' onclick='saveTextFromArea("+mouseY+","+mouseX+");'></div>";
                var appendString = textArea + saveButton;
                $("#main").append(appendString);
            } else {
                $('textarea#textareaTest').remove();
                $('#saveText').remove();
                //$('#textAreaPopUp').remove();
                var mouseX = e.pageX - this.offsetLeft + $("#c").position().left;
                var mouseY = e.pageY - this.offsetTop;
                //append a text area box to the canvas where the user clicked to enter in a comment
                var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+mouseY+"px;left:"+mouseX+"px;z-index:30;'><textarea id='textareaTest' style='width:100px;height:50px;'></textarea>";
                var saveButton = "<input type='button' value='save' id='saveText' onclick='saveTextFromArea("+mouseY+","+mouseX+");'></div>";
                var appendString = textArea + saveButton;
                $("#main").append(appendString);
            }
        });

        function saveTextFromArea(y,x){
            //get the value of the textarea then destroy it and the save button
            var text = $('textarea#textareaTest').val();
            $('textarea#textareaTest').remove();
            $('#saveText').remove();
            $('#textAreaPopUp').remove();
            //get the canvas and add the text functions
            var canvas = document.getElementById('c');
            var ctx = canvas.getContext('2d');
            var cw = canvas.clientWidth;
            var ch = canvas.clientHeight;
            canvas.width = cw;
            canvas.height = ch;
            //break the text into arrays based on a text width of 100px
            var phraseArray = getLines(ctx,text,100);
            // this adds the text functions to the ctx
            CanvasTextFunctions.enable(ctx);
            var counter = 0;
            //set the font styles
            var font = "sans";
            var fontsize = 12;
            ctx.strokeStyle = "rgba(0,0,0,1)";
            ctx.shadowOffsetX = 0;
            ctx.shadowOffsetY = 0;
            ctx.shadowBlur = 0;
            ctx.shadowColor = "rgba(0,0,0,1)";
            //draw each phrase to the screen, making the top position 20px more each time so it appears there are line breaks
            $.each(phraseArray, function() {
                //set the placement in the canvas
                var lineheight = fontsize * 1.5;
                var newline = ++counter;
                newline = newline * lineheight;
                var topPlacement = y - $("#c").position().top + newline;
                var leftPlacement = x - $("#c").position().left;
                text = this;
                //draw the text
                ctx.drawText(font, fontsize, leftPlacement, topPlacement, text);
                ctx.save();
                ctx.restore();
            });
            //reset the drop shadow so any other drawing don't have them
            ctx.shadowOffsetX = 0;
            ctx.shadowOffsetY = 0;
            ctx.shadowBlur = 0;
            ctx.shadowColor = "rgba(0,0,0,0)";
        }

        function getLines(ctx,phrase,maxPxLength) {
            //break the text area text into lines based on "box" width
            var wa=phrase.split(" "),
            phraseArray=[],
            lastPhrase="",
            l=maxPxLength,
            measure=0;
            ctx.font = "16px sans-serif";
            for (var i=0;i<wa.length;i++) {
                var w=wa[i];
                measure=ctx.measureText(lastPhrase+w).width;
                if (measure<l) {
                    lastPhrase+=(" "+w);
                }else {
                    phraseArray.push(lastPhrase);
                    lastPhrase=w;
                }
                if (i===wa.length-1) {
                    phraseArray.push(lastPhrase);
                    break;
                }
            }
            return phraseArray;
        }
    </script>
    <script src="js/text.js"></script>
    <script src="js/js.js"></script>
</body>
解决方案

The reason is that the canvas size is set for each time. When that happens:

Source

So the first thing to do is to preset the size on the canvas element either in the element tag (as shown below) or in a parent scope in the code:

<div id="main">
    <canvas id="c" width=500 height=300></canvas>   <!-- any size you want -->
</div>

Then remove these lines from the JavaScript:

    function saveTextFromArea(y,x){
        ...snipped for example...
        var canvas = document.getElementById('c');
        var ctx = canvas.getContext('2d');
        var cw = canvas.clientWidth;
        var ch = canvas.clientHeight;
        //canvas.width = cw;             // remove this line
        //canvas.height = ch;            // remove this line

        ...snipped for example...

这篇关于将多个文本实例添加到HTML5画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:09