简体   繁体   English

将值从文本字段传递到HTML画布

[英]Passing values from text field to HTML canvas

I'm looking to pass co-ordinates from a text field into HTML5 canvas. 我希望将坐标从文本字段传递到HTML5画布。 I'm using the code below to draw a rectangle on the canvas. 我正在使用下面的代码在画布上绘制一个矩形。 The co-ordinates should be 0,0,50,50 坐标应为0,0,50,50

function displayObject(currentObject){
    var imageNumber = $(currentObject).find('div.objectDd input.objectImageNum').val();
    var objectCoordinates = $(currentObject).find('div.objectDd input.objectCoordinates').val();
    var imageId = "";
    var canvasId = "";
    var context = "";
    var canvas = "";


    if(imageNumber != "" && objectCoordinates != ""){
        imageId = "#imgNum".concat(imageNumber);
        canvasId = $('#objectData').find('#miImages '+imageId+' .imageContainer canvas').attr("id");
        canvas = document.getElementById(canvasId);
        context = canvas.getContext("2d");
        context.fillStyle = "#FF0000";
        context.fillRect(objectCoordinates);
    }
}

I've tried passing them as a variable objectCoordinates but the rectangle is not drawn. 我尝试将它们作为变量objectCoordinates传递,但未绘制矩形。

How can I pass what the user enters as co-ordinates? 如何传递用户输入的坐标?

Right now, objectCoordinates is a string. 现在,objectCoordinates是一个字符串。 You need to extract the numbers the user is passing in: 您需要提取用户传递的数字:

var coordinateArray = objectCoordinates.split(",")

And then pass them in one by one: 然后将它们一一传递:

context.fillRect(coordinateArray[0],
                 coordinateArray[1],
                 coordinateArray[2],
                 coordinateArray[3])

Also, there's no need to initialize your variables with strings, especially the ones like canvas and context which end up not being strings at all. 另外,也不需要用字符串初始化变量,尤其是像canvas和context这样的变量,它们最终根本不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM