0

我在网上找到了许多关于在 HTML 画布中拖放图像和形状的教程。但它们似乎都旨在移动页面加载时在画布内生成的对象。我正在构建一个应用程序,让用户单击虚拟键盘上的按钮,然后单击画布以显示相应的数字或字符。这是我的代码:

 <script type="text/javascript">
            var mathCanvas = document.getElementById("matharea");
            var ctx = mathCanvas.getContext("2d");
            ctx.font="20px Arial";

            var placementCallback = function(){}

            mathCanvas.onselectstart = function(){return false;}

            function insertOne(){placementCallback = function(x, y){ctx.fillText('1', x-6,y+6);}};
            function insertTwo(){placementCallback = function(x, y){ctx.fillText('2', x-6,y+6);}};
            function insertThree(){placementCallback = function(x, y){ctx.fillText('3', x-6,y+6);}};

            mathCanvas.onclick = function(event){
                placementCallback(event.offsetX, event.offsetY);
            }
</script>

我删掉了一些插入函数以使其更短(我的 HTML 中的按钮具有调用这些函数的 onclick 属性)。我需要能够选择放置在屏幕上的字符并实现拖放和删除功能,但我想不出一种方法来处理页面加载后放置在屏幕上的文本(我'我对 Javascript 相当陌生)。我该怎么做?我不指望任何人给我代码来做到这一点,但如果我能朝着正确的方向前进,那就太好了。

4

2 回答 2

0

问题是画布是即时模式。无论你告诉它放在画布上,它都会立即放在画布上。它不会让您以任何方式、形状或形式修改该值。

可以把它想象成 MS Paint(或您的操作系统的等价物)和 Photoshop 之间的区别。
在 PS 中,您可以拥有可以四处移动和编辑的图层,当您决定完成图像时,您可以保存它并将所有数据展平。

当您在 MS Paint 中制作图像时,只要您单击或键入,您放在那里的那个东西就在那里,并且它不会移动/被编辑,除非您擦除它、在它上面绘制或在一个部分周围绘制一个矩形并且移动整个矩形(包括您要编辑的内容周围的像素)。

只需调用 fillText 就会在那个瞬间画出文字,但不会记住它画了什么,它在哪里,它是什么,文本与周围像素有何不同,等等。

因此,您的通用解决方案是您需要将文本转换为对象,然后将这些对象的一个​​方面(文本内容)绘制到屏幕上。

如果您的文本发生更改,您可以在对象中进行更改,然后重新绘制它(因为您的对象将存储其XY坐标,并将使用context.measureText(textObj.text).width方法/属性存储其宽度值),当您单击画布时,您可以检查单击的坐标,如果这些坐标与您的文本对象存储的坐标相交,那么您可以修改其在屏幕上的位置。

在这方面,您应该查看那些处理画布上拖动对象的示例。
单击按钮应被视为创建其中一个对象的一种方式。

于 2012-11-15T19:16:44.040 回答
-1

我知道这是很多代码......但我不想通过它..这是我很久以前构建的东西的一部分......只需复制并粘贴到一个 html 文件中......我希望它帮助您满足您的需求:

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>      

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js" type="text/javascript"></script>
        <script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.2.js" type="text/javascript"></script>
        <script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/minified/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
        <script>

        ;(function($) {

        $.fn.insertAtCaret = function (myValue) {

        return this.each(function() {

        //IE support
        if (document.selection) {

        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();

        } else if (this.selectionStart || this.selectionStart == '0') {

        //MOZILLA / NETSCAPE support
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;

        } else {

        this.value += myValue;
        this.focus();
        }
        });
        };

        })(jQuery);


        $(function go_prev() {
        //When you click on a link with class of poplight and the href starts with a # 
        $('a.poplight[href^=#]').click(function() {
            var popID = $(this).attr('rel'); //Get Popup Name
            var popURL = $(this).attr('href'); //Get Popup href to define size

            //Pull Query & Variables from href URL
            var query= popURL.split('?');
            var dim= query[1].split('&');
            var popWidth = dim[0].split('=')[1]; //Gets the first query string value

            //Fade in the Popup and add close button
            $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
            //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
            var popMargTop = ($('#' + popID).height() + 90) / 2;
            var popMargLeft = ($('#' + popID).width() + 80) / 2;
            //Apply Margin to Popup
            $('#' + popID).css({
                'top' : 10,
                'margin-left' : -popMargLeft
            });

            //Fade in Background
            $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
            $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 

            return false;
        });

        //Close Popups and Fade Layer
        $('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
            $('#fade , .popup_block').fadeOut(function() {
                $('#fade, a.close').remove();  //fade them both out
            });
            return false;
        });
        });
        </script>



        <script>
        var NumIms = 0;
        var NumTxts = 0;


        //IMAGE VARIABLES
        var ImIds=[];
        var ImNm=[];
        var ImWdth=[];
        var ImHght=[];


        //TEXT VARIABLES
        var TxtIds=[];
        var Txt=[];
        var TxtFnt=[];
        var TxtCol=[];
        var TxtSz=[];


        var MyWidth;
        var MyHeight;
        var img;


        function MoveOver(id,Rid) {
            var img = new Image();
            img.src = Rid;
            MyWidth = img.width;
            MyHeight = img.height;
                $("#UpIm" + id).append("W=" + MyWidth + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;H=" + MyHeight);
                $("#containment-wrapper").append('<div id="AdIm' + id + '" class="draggable ui-widget-content" style="width:' + MyWidth + 'px; height:' + MyHeight + 'px;  background-image: url(' + Rid + '); position:absolute; left:18px; top:18px;"></div>');


                ImIds[id]="AdIm" + id;
                ImNm[id]=Rid;
                ImWdth[id]=MyWidth;
                ImHght[id]=MyHeight;

                $( "#AdIm" + id ).draggable();
                var f = document.getElementById('UpIm' +id);
                var Olddiv = document.getElementById('ul' + id);
                f.removeChild(Olddiv);
        }
        </script>
        <script>
        function removeIm(id) {
            var f = document.getElementById('files');
            var Folddiv = document.getElementById('UpIm' + id);
            f.removeChild(Folddiv);

            var d = document.getElementById('containment-wrapper');
            var Dolddiv = document.getElementById('AdIm' + id);
            d.removeChild(Dolddiv);
            ImIds.splice(id,1,"deleted");

        }
        </script>


        <script type="text/javascript" >
        var iid = -1;
        var pic_real_width, pic_real_height, img;

        function removeFormIm(Rid,id) {
            var f = document.getElementById('files');
            var Folddiv = document.getElementById('UpIm' + id);
            f.removeChild(Folddiv);

            var d = document.getElementById('containment-wrapper');
            var Dolddiv = document.getElementById('AdIm' + id);
            d.removeChild(Folddiv);
        }

        </script>


        <style>
        #containment-wrapper { width: 845px; height:150px; border:2px solid #ccc; }

        #fade { /*--Transparent background layer--*/
            display: none; /*--hidden by default--*/
            background: #000;
            position: fixed; left: 0; top: 0;
            width: 100%; height: 100%;
            opacity: .80;
            z-index: 9999;
        }
        .popup_block{
            display: none; /*--hidden by default--*/
            background: #fff;
            padding: 20px;
            border: 20px solid #ddd;
            float: left;
            font-size: 1.2em;
            position: fixed;
            top: 50%; left: 50%;
            z-index: 99999;
            /*--CSS3 Box Shadows--*/
            -webkit-box-shadow: 0px 0px 20px #000;
            -moz-box-shadow: 0px 0px 20px #000;
            box-shadow: 0px 0px 20px #000;
            /*--CSS3 Rounded Corners--*/
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
        }


        .t_t{
            display: none; /*--hidden by default--*/
            background: #fff;
            padding: 20px;
            border: 20px solid #ddd;
            float: left;
            font-size: 1.2em;
            position: fixed;
            top: 50%; left: 50%;
            z-index: 99999;
            /*--CSS3 Box Shadows--*/
            -webkit-box-shadow: 0px 0px 20px #000;
            -moz-box-shadow: 0px 0px 20px #000;
            box-shadow: 0px 0px 20px #000;
            /*--CSS3 Rounded Corners--*/
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
        }
        img.btn_close {
            float: right;
            margin: -55px -55px 0 0;
        }
        /*--Making IE6 Understand Fixed Positioning--*/
        *html #fade {
            position: absolute;
        }
        *html .popup_block {
            position: absolute;
        }
        </style>


        <script>
        function changeTxt(id){
            var my_txt;
            my_txt =  document.getElementById('TxtIn' + id).value;
            document.getElementById('AdText' + id).innerHTML = my_txt;
            Txt[id] = my_txt;
            }
        </script>
        <script>
        function makebold(id){
        $('#TxtIn' + id).insertAtCaret('<b></b>');
        changeTxt(id);
            }

        function makeitalic(id){
        $('#TxtIn' + id).insertAtCaret('<i></i>');
        changeTxt(id);
            }

        function makecenter(id){

            var my_txt;
            my_txt =  document.getElementById('TxtIn' + id).value;
            $("textarea#TxtIn" + id).val('<center>' + my_txt + '</center>');
            changeTxt(id)
            }

        function makebr(id){
        $('#TxtIn' + id).insertAtCaret('<br>');
        changeTxt(id);
            }

        function makelink(id){
            get_color = document.getElementById('fcolor' + id).value;
            $('#TxtIn' + id).insertAtCaret('<a href="http://" style="text-decoration:none; color:#' + get_color + ';"></a>');
            changeTxt(id);
            }
            function makeh2(id){
        $('#TxtIn' + id).insertAtCaret('<H2></H2>');
        changeTxt(id);
            }
            function makeh3(id){
        $('#TxtIn' + id).insertAtCaret('<H3></H3>');
        changeTxt(id);
            }
        </script>
        <script>
        function callFontType(id){
            var type;
            type = document.getElementById('ftype' + id).value;
            document.getElementById('AdText' + id).style.fontFamily=type;
            TxtFnt[id] = type;
            }
        </script>

        <script>
        function CxColor(id){
            var Clor;
            Clor = document.getElementById('fcolor' + id).value;
            Clor = '#' + Clor;
            document.getElementById('AdText' + id).style.color=Clor;
            TxtCol[id] = Clor;
            }
         </script>

        <script>
        function changeFSize(id){

            var my_size;
            my_size =  document.getElementById('SizeIn' + id).value;
            my_size = my_size + 'px';
            document.getElementById('AdText' + id).style.fontSize = my_size;
            TxtSz[id] = my_size;
            }
        </script>

        <script>
        var id = -1;
                function addFormField() {
        id = id + 1;
        $("#divTxt").append("<span id='row" + id + "'><small>Add: to textbox:</small><input value=\"b\" onclick=\"makebold(" + id + ")\" title=\"bold: &lt;b&gt;text&lt;/b&gt;\" type=\"button\"><input value=\"i\" onclick=\"makeitalic(" + id + ")\" title=\"italic: &lt;i&gt;text&lt;/i&gt;\" type=\"button\"><input value=\"center\" onclick=\"makecenter(" + id + ")\" title=\"center: &lt;center&gt;text&lt;/center&gt;\" type=\"button\"><input value=\"BR\" onclick=\"makebr(" + id + ")\" title=\"BR: &lt;br&gt;\" type=\"button\"><input value=\"link\" onclick=\"makelink(" + id + ")\" title=\"link: &lt;a href= &gt;URL&lt;/a&gt;\" type=\"button\"><input value=\"H2\" onclick=\"makeh2(" + id + ")\" title=\"H2: &lt;H2&gt;text&lt;/H2&gt;\" type=\"button\"><input value=\"H3\" onclick=\"makeh3(" + id + ")\" title=\"H3: &lt;H3&gt;text&lt;/H3&gt;\" type=\"button\"><br><table><tr><td><a onClick='removeFormField(\"#row" + id + "\",\"" + id + "\"); return false;'>REMOVE</a></td><td>&nbsp;&nbsp;<textarea cols=50 rows=5 name='txt[]' id='TxtIn" + id + "'  onKeyUp=\"changeTxt(" + id + ");\">Text " + id + "</textarea></td><td>Font:<select onChange=\"callFontType(" + id + ");\" id=\"ftype" + id + "\"><option value=\"Arial, Helvetica, sans-serif\">Arial</option><option value=\"Impact, Charcoal, sans-serif\">Impact</option><option value=\"Palatino Linotype, Book Antiqua, Palatino, serif\">Palatino</option><option value=\"Tahoma, Geneva, sans-serif\">Tahoma</option><option value=\"Century Gothic, sans-serif\">Century Gothic</option><option value=\"Lucida Sans Unicode, Lucida Grande, sans-serif\">Lucida Grande</option><option value=\"Arial Black, Gadget, sans-serif\">Arial Black</option><option value=\"Times New Roman, Times, serif\">Times New Roman</option><option value=\"Arial Narrow, sans-serif\">Arial Narrow</option><option value=\"Verdana, Geneva, sans-serif\">Verdana</option><option value=\"Copperplate, Copperplate Gothic Light, sans-serif\">Copperplate</option><option value=\"Lucida Console, Monaco, monospace\">Lucida Console</option><option value=\"Gill Sans, Gill Sans MT, sans-serif\">Gill Sans</option><option value=\"Trebuchet MS, Helvetica, sans-serif\">Trebuchet</option><option value=\"Courier New, Courier, monospace\">Courier New</option><option value=\"Georgia, Serif\">Georgia</option></select><br>Color: <input id=\"fcolor" + id + "\" class=\"color\" value=\"000000\"><img src=\"go.png\" style=\"vertical-align:middle;\" onClick='CxColor(" + id + ");'><br>Size: <input type='text' size='4' value=\"12\" name='txt[]' id='SizeIn" + id + "'  onKeyUp=\"changeFSize(" + id + ");\"></td></tr></table><br><hr style=\"width:800px; float:left;\"><br></span>");
        $("#containment-wrapper").append('<span id="AdText' + id + '" class="draggable ui-widget-content" style="position:absolute; left:18px; top:18px; font-size:16px; font-family:Arial, Helvetica, sans-serif;">Text ' + id + '</span>');
        $( "#AdText" + id ).draggable();//{ containment: "#containment-wrapper", scroll: true }

        $('#fcolor' + id).load(jscolor.init());

        TxtIds[id] = "AdText" + id;
        Txt[id] = "Ad Text";
        TxtFnt[id] = "Arial";
        TxtCol[id] = "#000000";
        TxtSz[id] = "16";


        $('#row' + id).highlightFade({
            speed:1000
        });
        document.getElementById("id").value = id;
    }
        function removeFormField(Rid,id) {
            $(Rid).remove();
            var d = document.getElementById('containment-wrapper');
            var olddiv = document.getElementById('AdText' + id);
            d.removeChild(olddiv);
            TxtIds.splice(id,1,"deleted");
        }
        function GetURL(id) {

                var gurl;
                var Ims = "";
                var len=ImIds.length;
                NumIms = 0;
                NumTxts = 0;

                //############ Start Get Images for URL ##############
                for(var i=0; i<len; i++) {
                NumIms++;
                var value = ImIds[i];
                Ims += '&ImName' + i + '=' + value;
                if (value != "deleted"){

                value = ImNm[i];
                Ims += '&ImNm' + i + '=' + value;
                value = ImWdth[i];
                Ims += '&ImWidth' + i + '=' + value;
                value = ImHght[i];
                Ims += '&ImHeight' + i + '=' + value;
                value = $('#AdIm' + i).position().left - $('#AdIm' + i).closest('#containment-wrapper').position().left;
                Ims += '&ImLt' + i + '=' + value;
                value = $('#AdIm' + i).position().top - $('#AdIm' + i).closest('#containment-wrapper').position().top;
                Ims += '&ImTop' + i + '=' + value;
                }
                }
                //########### End Get Images For URL #####################
                len=TxtIds.length;
                //############ Start Get Texts for URL ##############
                for(var i=0; i<len; i++) {
                NumTxts++;
                var value = TxtIds[i];
                Ims += '&TxtName' + i + '=' + escape(value);
                if (value != "deleted"){
                value = Txt[i];
                Ims += '&Txt' + i + '=' + escape(value);
                value = TxtFnt[i];
                Ims += '&TxtFnt' + i + '=' + escape(value);
                value = TxtCol[i];
                value = value.substring(1);
                Ims += '&TxtCol' + i + '=' + escape(value);
                value = TxtSz[i];
                Ims += '&TxtSz' + i + '=' + escape(value);
                value = $('#AdText' + i).position().left - $('#AdText' + i).closest('#containment-wrapper').position().left;
                Ims += '&TxtLt' + i + '=' + value;
                value = $('#AdText' + i).position().top - $('#AdText' + i).closest('#containment-wrapper').position().top;
                Ims += '&TxtTop' + i + '=' + value;
                }
                }
                //########### End Get Texts For URL #####################





                gurl = "ad.php?AdType=hero&ImNum=" + NumIms + "&TxtNum=" + NumTxts;
                gurl = gurl + Ims;
                //alert(gurl);gurl = escape( gurl );
                $("#genurl" + id).html('<textarea id="fe_text" cols=50 rows=5 name="ad_url">' + gurl + '</textarea><br><br><table><tr><td><font style="font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#009999">Preview Gernerated Ad:</font></td><td><a href="' + gurl + '" target="_blank"><img src="view.png"></a></td></tr></table><br>');

            }


        </script>

           <script type="text/javascript">
            $(document).ready(function(){
                $("#myform1").validate({
                    debug: false,
                    submitHandler: function(form) {
                        // do other stuff for a valid form
                        $.post('process.php', $("#myform1").serialize(), function(data) {
                            $('#results').fadeIn('fast');
                            var mySplitResult = data.split("|||");
                        if(mySplitResult[1] !== "fail" && mySplitResult[1] !== "disable"){
        $('#upd1').html('<textarea id="fe_text" cols=50 rows=5 readonly="readonly">' + mySplitResult[1] + '</textarea><br />');
                        }
                        $('#results').html(mySplitResult[0]);
                            $('#prev1').html(mySplitResult[1]);
                                setTimeout(function() {
                                $('#results').fadeOut('slow');
                                }, 2500);


                        });
                    }
                });
            });



            </script>

        <script type="text/javascript" src="jscolor.js"></script>

        </head>

        <body>

        <div id="containment-wrapper">
        <!--<span id="AdText0" class="draggable ui-widget-content">For Testing ...  </span> -->
        </div>

        <div style="margin-left:50px;">
        <center><p style="font-family:Arial, Helvetica, sans-serif; font-size:24px; color:#FF0099">Text Field Input</p>
        <p><a href="#" onClick="addFormField(); return false;"  style="font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#6633FF;">Add Text Field</a></p></center>
        <form action="#" method="get" id="form1" style="font-family:Arial, Helvetica, sans-serif; font-size:16px;">
        <input type="hidden" id="id" value="1">
        <div id="divTxt"></div>
        </form>
        </div>





        <!-- End Hidden Divs -->
        </body>
        </html>
于 2012-11-14T23:32:12.583 回答