在JavaScript中用画布绘制矩形 - 定义矩形起点

时间:2014-07-16 14:52:49

标签: javascript canvas dimensions

这是我的谜题。我使用来自在线资源的一些代码使用画布绘制一个矩形,并一直在调整它以满足我的需要。原始代码工作正常,但它清楚地编码为从窗口的左上角开始;我从代码中了解到的很多。由于我的页面要求它相对于画布位置而不是窗口,这对我来说是一个问题。单击矩形开始时,实际矩形开始在光标下方画一段距离;然而,向下和向右,画布来自(0,0)。如何让它将画布视为用于定义起点的窗口?

JavaScript的:

   function getarea() {
         var wid = document.getElementById('wid').value;
         var hgt = document.getElementById('hgt').value;
         var area = (wid*hgt)
         var perim = (+wid + +hgt + +wid + +hgt)
         window.document.getElementById('area').innerHTML = area;
         window.document.getElementById('perim').innerHTML = perim;
      }


var rect;
var canvas;
var context;
var dragging;

function Point(x, y) {
    this.x = x;
    this.y = y;
}

function Size(width, height) {
    this.width = width;
    this.height = height;
}

function Rectangle(start, size) {
    this.start = start;
    this.size = size;
}

function init() {
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");

    canvas.addEventListener("mousedown", startDragging, false);
    canvas.addEventListener("mouseup", stopDragging, false);
    canvas.addEventListener("mousemove", moved, false);

    var start = new Point(0, 0);
    var size = new Size(0, 0);
    rect = new Rectangle(start, size);


}

function startDragging(event) {
clearRect(rect);
    dragging = true;

    // initialize start point
    var box=canvas.getBoundingClientRect();
    var offsetX=box.left;
    var offsetY=box.top;

    var mouseX = parseInt(event.clientX-offsetX);
    var mouseY = parseInt(event.clientY-offsetY);

    rect.start.x = mouseX;
    rect.start.y = mouseY;


    // initialize size
    rect.size.width = 0;
    rect.size.height = 0;
}

function stopDragging(event) {
    dragging = false;
}

function moved(event) {
    if(!dragging) return;

    var box=canvas.getBoundingClientRect();
    var offsetX=box.left;
    var offsetY=box.top;

    var mouseX = parseInt(event.clientX-offsetX);
    var mouseY = parseInt(event.clientY-offsetY);

    clearRect(rect);
    rect.size.width = event.pageX - rect.start.x;
    rect.size.height = event.pageY - rect.start.y;
    drawRect(rect);
}

function clearRect(rect) {
    context.clearRect(rect.start.x, rect.start.y, rect.size.width, rect.size.height);
}

function drawRect(rect) {
    context.fillRect(rect.start.x, rect.start.y, rect.size.width, rect.size.height);
}

HTML(通常与JavaScript问题无关,但由于HTML中定义的空间量与问题有关,因此我将其包括在内。我怀疑这很重要,但以防万一。):

    <html>
<head>
<script src="week5js.js"></script>
<link rel="stylesheet"href="assignment5.css"/>

<link href="assignment5.css" rel="stylesheet" type="text/css">

</script>

</head>


<header>
<center>
Week 6: Unit 6 - Assignment 5
</center>
</header>


<body onload="init()">

    <form id="areaform">
      <label for="width">Width:</label>
      <input id="wid" name="width" type="number">
      &nbsp
      &nbsp
      <label for="height">Height:</label>
      <input id="hgt" name="height" type="number">
      <br></br>
      <label for="area1">Area:</label>
      <output id="area"></output>
      <br></br>
      <label for="perimeter1">Perimeter:</label>
      <output id="perim"></output>
      <br></br>
      <button onclick="getarea()" type="button">Get Area</button>
    </form>


<canvas id="canvas" width="673" height="550"></canvas>
</body>

</html>

CSS

canvas {
    background-color: #F0F0F0;
    border: 1px solid;
}

header{

background-color: yellow;
padding:15px;
margin:30px;
font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
font-size:25px;
background-color:#F0F0F0;
border: 1px solid;

}

body{
max-width:50%;
padding:25px;
margin:20px;
font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
font-size:16x;
border: 2px dotted;
box-shadow: 2px 2px 4px #404040;
}

body img{

max-width:100%;

}

所以,总结一下:我需要能够从一个站点绘制一个矩形,当我这样做时,矩形起始点受到画布与窗口的关系的影响并弄乱所有东西并将矩形放在不同的位置不是预期的。我需要矩形从光标开始。

谢谢!

2 个答案:

答案 0 :(得分:0)

使用相对于画布的鼠标坐标:

var rect;
var canvas;
var context;
var dragging;

function Point(x, y) {
    this.x = x;
    this.y = y;
}

function Size(width, height) {
    this.width = width;
    this.height = height;
}

function Rectangle(start, size) {
    this.start = start;
    this.size = size;
}

function init() {
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");

    canvas.addEventListener("mousedown", startDragging, false);
    canvas.addEventListener("mouseup", stopDragging, false);
    canvas.addEventListener("mousemove", moved, false);

    var start = new Point(0, 0);
    var size = new Size(0, 0);
    rect = new Rectangle(start, size);
}

function startDragging(event) {
    dragging = true;

    // initialize start point
    var box=canvas.getBoundingClientRect();
    var offsetX=box.left;
    var offsetY=box.top;

    var mouseX = parseInt(event.clientX-offsetX);
    var mouseY = parseInt(event.clientY-offsetY);

    rect.start.x = mouseX;
    rect.start.y = mouseY;

    // initialize size
    rect.size.width = 0;
    rect.size.height = 0;
}

function stopDragging(event) {
    dragging = false;
}

function moved(event) {
    if(!dragging) return;

    var box=canvas.getBoundingClientRect();
    var offsetX=box.left;
    var offsetY=box.top;

    var mouseX = parseInt(event.clientX-offsetX);
    var mouseY = parseInt(event.clientY-offsetY);

    clearRect(rect);
    rect.size.width = mouseX - rect.start.x;
    rect.size.height = mouseY - rect.start.y;
    drawRect(rect);
}

function clearRect(rect) {
    context.clearRect(rect.start.x, rect.start.y, rect.size.width, rect.size.height);
}

function drawRect(rect) {
    context.fillRect(rect.start.x, rect.start.y, rect.size.width, rect.size.height);
}

答案 1 :(得分:0)

您只需从位置计算中减去画布的左上角位置即可。

将此全局添加到您的设置中:

var canvasBox = document.getElementsByTagName('canvas')[0].getBoundingClientRect();

如果你已经在函数中包装了你的设置,请使用window.canvasBox来使其成为全局的。 然后使用此函数计算新的相对位置。

function getPos(event)
{
    return {"x":event.clientX - canvasBox.left,"y":event.clientY-canvasBox.top};
}

像这样使用

var mousePos = getPos(event);
//mousePos.x
//mousePos.y

这是一个用于处理触摸的扩展片段,它已经从我的图书馆进行了编辑,因此请注意拼写错误!

function init()
{
    window.canvas = document.getElementsByTagName('canvas')[0];
    window.context = canvas.getContext('2d');
    window.canvasBox = canvas.getBoundingClientRect();
    canvas.ontouchstart = function(event){start(event);};
    canvas.ontouchmove = function(event){update(event);};
    canvas.ontouchleave = function(event){end(event);};
    canvas.onmousedown = function(event){start(event);};
    canvas.onmousemove = function(event){update(event);};
    window.addEventListener('mouseup',function(event){end(event);},false);
    window.addEventListener('touchend',function(event){end(event);},false);
    window.addEventListener('touchcancel',function(event){end(event);},false);
}

function start(event)
{
    var position = getPos(event);
}
function update(event)
{
    var position = getPos(event);
}
function end(event)
{
    var position = getPos(event);
}

function getPos(event)
{
    event.preventDefault(); //stops a touch from scrolling the page etc
    var pos = {};
    if(typeof event.changedTouches !== "undefined") // check for preferred touch data
    {   if(event.changedTouches.length !== 0){ // check to see if there are any touches available
            pos.x = event.changedTouches[0].clientX;
            pos.y = event.changedTouches[0].clientY;
    }   }
    else if(typeof event.touches !== "undefined") // check for other touch data
    {   if(event.touches.length !== 0){ // check to see if there are any touches available
            pos.x = event.touches[0].clientX;
            pos.y = event.touches[0].clientY;
    }   }
    else if(typeof event.clientX !== "undefined") //check for mouse location
    {
        pos.x = event.clientX;
        pos.y = event.clientY;
    }
    else //set to null as a fallback
    {
        pos.x = null;
        pos.y = null;
    }
    if(pos.x!==null) // if we have a position, make it in canvas relative space
    {
        pos.x -= canvasBox.left; 
        pos.y -= canvasBox.top;
    }
    return pos; 
}