Creating a stylish border around an image using a JavaScript function

I am interested in creating a JavaScript function called addborder(y) that will add a yellow border to an image. This experiment aims to explore the process of manipulating images using JavaScript.

<!--HTML-->

<img id="img" src="http://pre01.deviantart.net/3d38/th/pre/f/2012/298/5/a/dubstep_wallpaper_by_theblazia-d5iwj4c.png" alt="boom boom boom" >

<p id="here"></p>

<Script>

var y = document.getElementById("img"); //Storing "img" element as variable y.

function addborder(x) {
  for (var pixel of x.values()) {
    //Loop through image pixels and change border to yellow
    if (
      pixel.getX() < 50 ||
      pixel.getX() > x.getWidth() - 50 ||
      pixel.getY() < 200 ||
      pixel.getY() > x.getHeight() - 50
    ) {
      pixel.setRed(255);
      pixel.setGreen(255);
      pixel.setBlue(255);
    }
  }
  document.getElementById("here").innerHTML = x; //Display modified image in paragraph

  //Is a return statement necessary?
}

Answer №1

Instead of using a complicated function to manipulate pixels directly, it's usually more efficient to simply use the .style property in JavaScript to change CSS properties.

For example, you can create a border easily with .style.border like this:

var image = document.getElementById('img');
image.style.border = 'thick solid #0000FF';
<img id="img" src="http://placehold.it/100">

I hope this tip is helpful for you!

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

Error encountered: LIBUSB_ERROR_NOT_SUPPORTED in the node escpos program

When attempting to print with a thermal printer using the node-escpos module, everything works well on Linux but I encounter an error on Windows. The error message reads: LIBUSB_ERROR_NOT_SUPPORTED. Error: LIBUSB_ERROR_NOT_SUPPORTED at Device.usb.Devi ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

TimePicker Component for ASP.Net MVC with Razor Syntax

I'm currently working on implementing a TimePicker using Razor and JQueryUI in my bootstrap website. While I have successfully created a DatePicker, I am facing difficulties in creating a separate TimePicker using two different TextBoxes instead of se ...

"Triggering the jQuery mouseout event following a resize of an element

I'm currently trying to develop a dynamic shopping cart widget. The concept is to have a box that displays the number of items in your cart, and when you click on it, it expands to show a detailed view of the cart contents. I've successfully man ...

"Is there a virtual keyboard available that supports multiple inputs and automatically switches to the next input when the maximum length

Looking to build a virtual keyboard with multiple inputs that automatically switch to the next input field after reaching the maximum length. Currently having an issue where I can only fill the first input and not the second one. Any assistance in resolvin ...

Using JavaScript with React to invoke an asynchronous action within a component

Within my class, I have implemented some asynchronous actions in the ComponentDidMount method. The code snippet looks like this: componentDidMount(){ // var my_call = new APICall() Promise.resolve(new APICall()).then(console.log(FB)) } class API ...

Having trouble navigating the Request and Response handling in Expressjs/Nodejs?

As I continue to delve deeper into this code, confusion seems to cloud my understanding. Here is the provided source: var express = require('express') , http = require('http') , server = express() ; var home = require('./ro ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

Combining multiple API requests using NodeJS

I'm currently experimenting with SteamAPI to enhance my understanding of NodeJS. My aim is to retrieve game information after making an initial request to obtain the player's profile and storing the game IDs in an array. However, I am facing a ch ...

What is the best way to give an input box an id/className/refs in React and then access it through a variable?

As a new React learner, I am diving into building my very first project - an expense tracker. Despite being close to finishing, I am struggling with incorporating ids and classNames in React. I've experimented with using refs, but unfortunately, it&ap ...

Importance of xpath:position and xpath:attribute

I'm currently developing a recording tool using JavaScript that is comparable to Selenium. When it comes to Playback, I require the XPath position and its attributes (shown in the screenshot below from Selenium). Can anyone provide guidance on how to ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...

experimenting with adding fresh choices to dropdown menu using ajax and jquery

When attempting to load a list of locations through ajax/jQuery, I encounter an issue. After typing a letter into the input field, the first response is displayed but subsequent responses are simply appended to it. I have tried using .html('') an ...

Challenges faced with JavaScript Ajax functionality

Currently, I am developing a custom HTTP client using JavaScript. Although my code appears to be correct, I keep receiving 404 errors for my requests. This code is being executed on a NodeJS (ExpressJS) server that includes a handler as shown below: app.p ...

Display Vue component using a string input

Is there a solution to make this non-functioning example work, or is its usage illegal? Vue.component('hello', { template: '<span>Hello world!</span>' }) Vue.component('foo', { data(){ return { ...

I'm intrigued by this maneuver, but I am uncertain about its safety when used in JavaScript

I am currently contemplating the safety and reliability of assigning a variable within an if statement across different browsers. If it proves to be safe, then I am inclined to proceed with its usage. The scenario involves reading the query string and che ...

I am experiencing an issue with my route where the Passport JWT req.user is unexpectedly undefined

Setting up JWT with my express app has been quite the challenge! Despite getting most of it working, I've encountered a strange issue. My register and login routes are generating valid tokens and authentication works fine in the '/users' rou ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

The value of document.readyState remains as 'complete' even while the page is still actively loading on the frontend

Below is the code I implemented to verify if the page has finished loading: JavascriptExecutor js = (JavascriptExecutor)Driver; pageLoadStatus = js.executeScript("return document.readyState").toString(); Despite still visibly loading, the document.readyS ...

I am receiving all NFT IDs when I should only be getting the ones that are associated with the current account

I am facing an issue where I am receiving all NFTs token IDs instead of just the one that belongs to the current account. The code snippet causing this problem is as follows: const { enableWeb3, account, isWeb3Enabled, Moralis, deactivateWeb3 } = useMorali ...