Draw rectangle using Canvas in JavaScript - define rectangle starting Pont


username

This is my conundrum. I used some code from online sources to draw rectangles using canvas and have been tweaking it to suit my needs. The original code works fine, but clearly encodes it from the top left corner of the window. I learned a lot from the code. This is a problem for me since my page requires it to be relative to the canvas position and not the window position. When you click on the start of the rectangle, the actual rectangle starts to draw some distance below the cursor. However, starting at (0,0), the canvas is further down and to the right. How can I make it see the canvas as a window for defining the starting point?

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 (Not normally relevant to JavaScript issues, but I'm including it because the amount of space defined in HTML is relevant to the issue. I doubt it's important, but just in case.):

    <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%;

}

So, in summary: I need to be able to draw a rectangle from the site, and when I do that, the starting point of the rectangle is affected by the canvas's relationship to the window, and messes everything up and places the rectangle in a different position than it was intended. I need the rectangle to start at the cursor.

Thanks!

Hovitia

Use canvas-relative mouse coordinates:

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);
}

Related


Javascript Canvas draw rectangle or circle

nameless I'm looking for a way to draw rectangles or circles "on the fly" on a canvas. I found various ways to fillRect()draw rectangles, but not in real time. I mean, being able mouseDown()to move it from one point to another point in the canvas, it defines t

Let user draw rectangle with mouse on canvas using Javascript

Cai Chongxin I will create a canvas so that the user can draw some rectangles in the canvas. When the user drags the mouse, it can display the rectangle. Likewise, it allows the user to draw one or more rectangles on the canvas. I found a solution like this: /

Let user draw rectangle with mouse on canvas using Javascript

Cai Chongxin I will create a canvas so that the user can draw some rectangles in the canvas. When the user drags the mouse, it can display the rectangle. Likewise, it allows the user to draw one or more rectangles on the canvas. I found a solution like this: /

Let user draw rectangle with mouse on canvas using Javascript

Cai Chongxin I will create a canvas so that the user can draw some rectangles in the canvas. When the user drags the mouse, it can display the rectangle. Likewise, it allows the user to draw one or more rectangles on the canvas. I found a solution like this: /

Let user draw rectangle with mouse on canvas using Javascript

Cai Chongxin I will create a canvas so that the user can draw some rectangles in the canvas. When the user drags the mouse, it can display the rectangle. Likewise, it allows the user to draw one or more rectangles on the canvas. I found a solution like this: /

Let user draw rectangle with mouse on canvas using Javascript

Cai Chongxin I will create a canvas so that the user can draw some rectangles in the canvas. When the user drags the mouse, it can display the rectangle. Likewise, it allows the user to draw one or more rectangles on the canvas. I found a solution like this: /

Draw rectangle on HTML using javascript

i love tacos I know there is a similar question here , but no question and no answer with any code. All I want to do is port this functionality into a 100% Javascript solution. Now I can draw a rectangle above the HTML content using PHP. I use CasperJS to scra

Trying to draw a rectangle on a canvas, preferably in Javascript?

Intuitive programming I'm trying to draw a rectangle like you do in Paint. But currently when I try to draw rectangles, this is what my canvas looks like - double painting, messy rectangles. Here's what my entire code looks like: (deleted code) How to draw a r

Draw rounded rectangle using RectF and canvas?

TokTok123 I am trying to draw a rounded rectangle using RectF and canvas.drawRoundRect(). Please see my code below: package com.example.test; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.graphics.Canvas

draw rectangle in canvas

125fur I can draw rectangle on video on canvas. But it's hidden behind the video but can't suggest how I should draw the rectangle on the video through the side.Pls like I can draw the code on the image. : <p>Video to use:</p> <video id="video1" controls wi

draw rectangle in canvas

125fur I can draw rectangle on video on canvas. But it's hidden behind the video but can't suggest how I should draw the rectangle on the video through the side.Pls like I can draw the code on the image. : <p>Video to use:</p> <video id="video1" controls wi

Draw resizable rectangle on canvas

Inde · 穆里罗 (Masinde Muliro) I am trying to draw a resizable rectangle on a canvas element. I check the position of the mouse relative to the rectangle on the screen and then update the width/height of the triangle the mouse falls into. So far I've managed to s

draw rectangle on canvas

Avsana Khan I'm trying to develop a ping pong game in Android where I will have two bats to hit the ball. I drew a bat on the canvas and it was placed at the far left of the screen. I need another bat on the far right of the screen, but every time the paddle i

draw rectangle on canvas

Avsana Khan I'm trying to develop a ping pong game in Android where I will have two bats to hit the ball. I drew a bat on the canvas and it was placed at the far left of the screen. I need another bat on the far right of the screen, but every time the paddle i

Draw resizable rectangle on canvas

Inde · 穆里罗 (Masinde Muliro) I am trying to draw a resizable rectangle on a canvas element. I check the position of the mouse relative to the rectangle on the screen and then update the width/height of the triangle the mouse falls into. So far I've managed to s

draw rectangle in canvas

125fur I can draw rectangle on video on canvas. But it's hidden behind the video but can't suggest how I should draw the rectangle on the video through the side.Pls like I can draw the code on the image. : <p>Video to use:</p> <video id="video1" controls wi

Canvas issue, unable to draw rectangle

Jose Jimenez I have the following code to draw a blue rectangle and a red line on a black background. function love.load() love.window.setMode(300,200,{fullscreen=false}) end function love.draw() love.graphics.setColor(0, 0, 255, 255) love.graphic

How to draw a rectangle with border on canvas?

je3rdty var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); //ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise); ctx.beginPath() ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled) ctx.arc(100,100,55,0,Math.PI*2, true)

Draw rectangle with fixed width canvas

Derek Palmer I'm trying to let the user draw a rectangle on an image inside a canvas using the mousemove event. It works fine with this code: HTML: <canvas id="canvas"></canvas> JavaScript: window.onload = drawCanvas('http://www.therebeldandy.com/wp-conte

Canvas issue, unable to draw rectangle

Jose Jimenez I have the following code to draw a blue rectangle and a red line on a black background. function love.load() love.window.setMode(300,200,{fullscreen=false}) end function love.draw() love.graphics.setColor(0, 0, 255, 255) love.graphic

How to draw a rectangle with border on canvas?

je3rdty var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); //ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise); ctx.beginPath() ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled) ctx.arc(100,100,55,0,Math.PI*2, true)

How to draw a rectangle with border on canvas?

je3rdty var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); //ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise); ctx.beginPath() ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled) ctx.arc(100,100,55,0,Math.PI*2, true)

How to draw a rectangle with border on canvas?

je3rdty var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); //ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise); ctx.beginPath() ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled) ctx.arc(100,100,55,0,Math.PI*2, true)

How to draw a rectangle with border on canvas?

je3rdty var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); //ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise); ctx.beginPath() ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled) ctx.arc(100,100,55,0,Math.PI*2, true)

How to draw a rectangle with border on canvas?

je3rdty var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); //ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise); ctx.beginPath() ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled) ctx.arc(100,100,55,0,Math.PI*2, true)

Draw rectangle with loaded pdf file in canvas using pdf.js

Sharma Vikram I am trying to draw rectangles on a pdf file. When I draw rectangles in pdf, the rectangles are not drawn correctly. I want to draw only one rectangle at a time, when I draw the new one, the old one should be deleted, but this is not happening. H