Is the performance of `fillRect` hindered when painting on a 3D model?

Currently, I am in the process of developing a painting-type application using three.js/canvas.

My goal is to enable users to paint directly onto a 3D model, updating the UV map accordingly.

https://i.sstatic.net/DfMvB.png

While I have achieved the desired functionality in my current version, I am facing performance issues.

In this iteration, I record the strokes on the 2D canvas and then project each pixel onto the model when drawing stops (on mouseup). I calculate the corresponding UV coordinates and use fillrect to draw the pixel in the correct position on the UV map.

Although this approach works, I believe there must be a more efficient method. Can anyone provide guidance on improving the efficiency?

for (var iy = 0; iy < height; iy++){
    for (var ix = 0; ix < width; ix++){

    var red = imgData.data[((width * iy) + ix) * 4];
    var green = imgData.data[(((width * iy) + ix) * 4) + 1];
    var blue = imgData.data[(((width * iy) + ix) * 4) + 2];
    var alpha = imgData.data[(((width * iy) + ix) * 4) + 3];

    array = getMousePosition( container, ix+300, iy+300);
    onClickPosition.fromArray( array );

    intersects = getIntersects( onClickPosition, arrayMesh );

    if ( intersects.length > 0 ){
        var uv = intersects[ 0 ].uv;
        intersects[ 0 ].object.material.map.transformUv( uv );
        currentPoint = { x: Math.round(uv.x*canvas.width), y: Math.round(uv.y*canvas.height) };
        ctx.fillRect(currentPoint.x, currentPoint.y, 1, 1);
    }

    }
 }

Answer №1

It seems like the texture you are working with is a canvas, as indicated by your use of fillrect to place a specific pixel on the UV map.

Instead of repetitively using fillrect many times, consider accessing the ImageData directly and manually setting the pixels. This method will be significantly faster for individual pixel updates, as it eliminates the need for function calls every time.

To optimize further, you could have the mouse input generate strokes on one canvas (often in grayscale), then project that canvas onto your model and UV map. You can then utilize it as a filter for blending paint colors or textures additively. This technique provides a simple way to apply an image to a model by painting the mask first and then incorporating the image accordingly.

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

Discover the joy of reading with wrap/unwrap to consume more content in less

I am experimenting with a 'read-more read-less' feature using a wrap method that currently only works for the 'show more' functionality. So, to clarify, if the text exceeds a certain length, I truncate it and insert a read-more-link ( ...

Having trouble with Javascript/ajax/php: data is successfully sent from server to client, but client to server communication is not working as

Apologies for the duplicate post (Admins, kindly remove the other one!). I've been receiving great assistance from you all and was hoping to seek your help once again with the following question: I am currently working on implementing AJAX by allowin ...

Is there a comparison you can make between v-for and a similar feature in Stencil? (such as a functionality akin to v-for

When working with arrays in Stencil, I need to repeat a specific element multiple times based on the array. In Vue, I typically use v-for for this purpose, but what is the equivalent in Stencil? ...

What causes the Error: ENOENT open error to occur when attempting to render a doT.js view?

My first experience with doT.js led me to create a basic server setup: 'use strict'; var express = require('express'); var app = express(); var doT = require('express-dot'); var pub = __dirname+'/public'; var vws ...

The functionality of making Slim POST requests is currently not functioning as expected within the Ionic

An issue is arising with my app that makes calls to a REST API using POST and GET methods. The app I'm developing with Ionic works perfectly when emulated using the command: ionic serve --lab However, when running the app on an actual device, calls ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

What is the best way to capture a screenshot of a website using its URL?

I've been curious about the possibility of capturing a screenshot of a remote website using only a URL and some JavaScript code. This functionality is often seen on bookmarking sites. I can't help but wonder if this is achieved through a virtual ...

Set the variable after catching it

Within my AngularJS application, I am utilizing a $watchCollection function to call the getBalance(address) function within the listener. $scope.$watchCollection('settings', function() { for (i = 0; i < $scope.settings['accounts&ap ...

What is the best way to save information from an ng-repeat loop into a variable before sending it to an API?

My goal is to store the selected value from ng-repeat in UI (user selection from dropdown) and assign it to a variable. function saveSelection() { console.log('inside function') var postToDatabase = []; vm.newApplicant.values ...

What could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...

How can you locate the position of a selector within a parent or set using jQuery

Could someone please help me determine the position of the current selector within its parent using jQuery? I need this information in order to effectively use the .insertAfter() and .insertBefore() methods to rearrange elements within their nested structu ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

Having trouble with the Twitter share count URL - seeking out other options

Previously, I utilized the following Javascript function to retrieve the Twitter share count for a URL. Unfortunately, Twitter has discontinued providing the share count. Is there a more effective alternative available? // Twitter Shares Count $.getJSON ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

When it comes to Redux, is it considered an anti-pattern to pass an event from a presentational component to a container component

As a newcomer to Redux, I am challenging myself to rebuild an old React app using this technology in order to gain proficiency. However, I am facing a significant challenge regarding where to place the logic within the application. My understanding is tha ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...

Node.js application experiencing bug with End of Line (EOL) not displaying correctly

I've encountered an issue with my node.js application that involves writing the following code: word_meaning = 'line 1' + os.EOL +'line 2'; When attempting to render this in an HTML file using the following code: <p> <% ...

perform the .then() function within a returned promise

Here is my code snippet: function scammer(message) { return new Promise((resolve,reject)=>{ if(condition){ if (condition) { bot.KickMember(params).then((message)=>{ console.log("kicked"); ...

How to make an AJAX request in jQuery / JavaScript after a specific time interval has passed

Here is the code snippet I'm working with: $('input.myinput').each(function(){ var id = $(this).val(); var myajax = function(){ $.ajax({ url: ajax_url, type: "GET", data: ({ code: id ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...