When I click the mouse, my drawing function starts lines from the top left corner instead of the latest point

http://codepen.io/FreelanceDev/pen/kLpJSf?editors=1010

You can find my CodePen project through the provided link.

While the HTML and CSS elements are working correctly, I am facing issues with the JavaScript functionality. The desired outcome should be drawing a line from the last clicked point.

The JavaScript code snippet in question is as follows -

var randomColor = function() {
    return '#' + Math.random().toString(16).slice(2, 8);
}

var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
color = randomColor();

var height = window.innerHeight
var width = window.innerWidth

canvas.width = width
canvas.height = height

var mouse = {};

var circle_count = 10;
var circles = [];

var generate = function() {
    for (var i = 0; i < circle_count; i++) {
        circles.push(new circle());
    }
}

setInterval(generate, 7500);

canvas.addEventListener('mousedown', getPosition, false);
canvas.addEventListener('touch', getPosition, false);

function getPosition(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;
}

canvas.addEventListener("mousedown", function() {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(mouse.x, mouse.y);
    ctx.stroke();
});

Answer №1

In order to properly apply a new position, it is essential to save the last clicked position, as demonstrated in the following example:

codepen.io/themeler/pen/XdxboL?editors=0010

Answer №2

With each occurrence of the mousedown event, the function ctx.moveTo(0, 0) is executed, positioning it in the top left corner.

To resolve this issue, simply remove the code from the mousedown event and place it outside:

ctx.beginPath();
ctx.moveTo(0, 0);

Check out the updated code on CodePen

Answer №3

Modify the mouse variable to choose where you want to start

let mouse = {x : 0, y : 0};

Next, adjust the event handler to keep track of the current position of the mouse

canvas.addEventListener('touch', action);
canvas.addEventListener("mousedown", action);

function action(e) {
    ctx.beginPath();
    ctx.moveTo(mouse.x, mouse.y);
    ctx.lineTo(e.pageX, e.pageY);
    ctx.stroke();
    mouse = {x: e.pageX, y: e.pageY};
}

FIDDLE

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

There are a few issues with certain Bootstrap elements such as the Navbar-collapse, p- classes, and small column images

I wanted to express my gratitude for all the incredible resources shared here. I have been working on sorting out some issues over the past few days. While Bootstrap seems to be functioning well in certain areas, it's not working as expected in oth ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Tips for creating an infinite repeating loop in jQuery

I'm attempting to create a jQuery infinite loop featuring images within a div. I've experimented with using the setInterval function, but encountered an issue where the animation starts after a 3-second delay and does not seamlessly repeat itself ...

What could be the reason for the lack of responsiveness in my input box?

http://jsfiddle.net/4ws3L6kn/1/ Can anyone help me figure out why this isn't responsive? What mistake did I make? <div id="DIV_1"> <div id="DIV_2"> <div id="DIV_3"> <button id="BUTTON_4"> ...

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

I have a JavaScript code that smoothly scrolls to different id's on a webpage, but I need assistance in adding an exception for a particular id

I'm looking to incorporate smooth scrolling for all hash links in my JavaScript. However, I need the id=nav and its resulting hash link, /#nav, to be exempt from this functionality as it interferes with the menu responsiveness. Can someone provide gui ...

Fetching database entries upon page load instead of using the keyup function in JavaScript

Here is an HTML form input provided: <input type="text" id="username" value=""> In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records: $(function(){ //var socket = ...

Implementing specific CSS styles for images that exceed a certain size limit

Currently, I am facing a dilemma as I work on developing a basic iPhone website that serves as a port for my blog. The main issue I am encountering is the need to add a border around images above a specific size and center them in order for the blog to hav ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

The text and buttons exceed the size limits of the popup box

Currently, I am tasked with updating an old website that includes a popup box containing an iFrame and nested tables. The content within these tables consists of text and two input boxes at the bottom. Everything within the box looks fine on screen resolu ...

Populating a read-only field with information from a database upon selecting an option

My goal is to select a name from an option field and then display the user's ID in a non-editable field. Essentially, when I choose a username, I want to automatically show their user ID. Below is the PHP and HTML code I currently have: <form id=" ...

What is the most effective method for configuring an npm module?

I need help with configuring an npm module that I'm developing. The module includes two functions called notify.sms.send() and notify.email.send(), as well as an abstract function notify.send() that can call either or both of these functions. To hand ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Safari is not properly rendering a React/Next.js website (showing a blank page)

Recently, I've been facing a frustrating bug on my Next.js website. When I try to open it in Safari, there's a 50/50 chance that it will either load correctly or show a blank page with faint outlines of components but no text. This issue occurs o ...

What is the best way to retrieve data based on conditions in React?

I'm currently learning React and trying to pass props from a parent component (table row) to a child Modal component. Inside the child component, I want to fetch data based on the props provided. I have created a custom hook called useFetch that store ...

Assigning the image source to match the image source from a different website using the image ID

Would it be possible to retrieve the URL of an image from a different webpage using its img ID, and then implement it as the image source on your own website? This way, if the image is updated on the original site, it will automatically update on yours as ...

Equal-height list items in a multi-column unordered list

A multi-column unordered list has been created. Below is the HTML code: <ul> <li>Antelope</li> <li>Bison</li> <li>Camel</li> <li>Deer</li> <li>Eland</li> <li>Gazell ...

How can I design a search box similar to the one on the android.com website?

Is it possible to replicate the search box effect on the Android website, where the menu items fade out and the search box expands upon clicking the search icon?view image here See the difference before and after clicking the search icon ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...