ScreenshotNeo

BlogHow-to

How to Embed and Transform Images with jQuery

Add and update images with jQuery, make them responsive, and learn when CSS is enough and when canvas is needed for a real pixel transformation.

By the ScreenshotNeo team4 October 20269 min read

Use jQuery to create, insert, and update an <img> element. Use CSS for display-only resizing or cropping. If you need a new bitmap with pixels actually scaled, cropped, or edited, load the image and draw it to the Canvas API. jQuery manipulates the page; it does not provide pixel-editing operations.

This guide covers image insertion, source changes, responsive markup, visual sizing and cropping, and canvas export, including load timing and cross-origin constraints.

1. Add an image to the page with jQuery

Create an image element, set its attributes, and append it to a container. Setting attributes through jQuery APIs also avoids building HTML strings from untrusted values.

<div id="gallery"></div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="app.js"></script>
const $image = $("<img>").attr({
  src: "/images/landscape.jpg",
  alt: "Snow-covered ridge at sunrise",
  width: 1200,
  height: 800
});

$("#gallery").append($image);

Use a meaningful alt value when the image communicates information. For a purely decorative image, use alt="". Width and height give the browser the image’s intrinsic ratio so it can reserve layout space before the file loads.

Insert data safely

If the URL or description comes from user input, set them as attributes instead of concatenating that input into an HTML string:

function addImage(container, imageUrl, description) {
  const $image = $("<img>").attr({
    src: imageUrl,
    alt: description
  });

  $(container).append($image);
}

Validate URLs according to your application’s rules before using user-provided values. DOM APIs prevent the specific risk of treating a value as markup, but they do not decide which image URLs your application should accept.

2. Change an existing image’s source

Set both src and alt when replacing an image so its text description stays accurate:

$("#preview").attr({
  src: "/images/alternate.jpg",
  alt: "A close-up of the alternate subject"
});

A source change starts an image resource fetch. If later code needs to draw that image to a canvas, wait for the new image to load and handle a failed request. Do not assume that setting src means the image is immediately drawable.

3. Resize or crop the displayed image with CSS

For responsive display, constrain the image to its container while preserving its ratio:

.gallery-image {
  display: block;
  max-width: 100%;
  height: auto;
}

To fill a fixed-size frame, use object-fit: cover. This crops the displayed view; it does not create a cropped image file.

<div class="thumbnail-frame">
  <img class="thumbnail" src="/images/landscape.jpg"
       alt="Snow-covered ridge at sunrise" width="1200" height="800">
</div>
.thumbnail-frame {
  width: 320px;
  height: 200px;
  overflow: hidden;
}

.thumbnail {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

Change object-position to keep a different part of the source in view, for example object-position: 70% 30%. Use jQuery .css() when a presentation style needs to change dynamically:

$("#preview").css({
  width: "320px",
  height: "200px",
  objectFit: "cover",
  objectPosition: "70% 30%"
});

Prefer a stylesheet for stable layout rules and use jQuery styling for behavior-driven changes. Both approaches affect presentation, not the downloaded source bitmap.

4. Use responsive image sources

For different image sizes, provide candidates with srcset and describe the rendered slot with sizes. The browser can choose an appropriate resource for the layout and device conditions. Keep a fallback src, and do not mix width (w) and density (x) descriptors in one srcset.

<img
  src="/images/landscape-800.jpg"
  srcset="/images/landscape-400.jpg 400w,
          /images/landscape-800.jpg 800w,
          /images/landscape-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, 800px"
  width="1200"
  height="800"
  alt="Snow-covered ridge at sunrise">

Use <picture> when source selection depends on art direction or supported formats. jQuery can set these attributes too, but HTML markup is usually clearer when the choices are static:

<picture>
  <source media="(max-width: 600px)" srcset="/images/landscape-portrait.jpg">
  <source type="image/webp" srcset="/images/landscape.webp">
  <img src="/images/landscape.jpg" width="1200" height="800"
       alt="Snow-covered ridge at sunrise">
</picture>

Native lazy loading can defer offscreen images at the browser’s discretion. Use it for content that starts outside the initial view, and avoid lazy-loading a likely above-the-fold lead image:

$("#below-fold-image").attr("loading", "lazy");

5. Transform pixels with canvas

To produce a resized or cropped bitmap, use the Canvas API’s drawImage(). The example below loads a same-origin image, scales it to a 600-by-400 canvas, and exports a JPEG data URL.

<img id="source" src="/images/landscape.jpg" alt="" hidden>
<canvas id="output" width="600" height="400"></canvas>
<button id="download" type="button">Download crop</button>
const image = document.getElementById("source");
const canvas = document.getElementById("output");
const context = canvas.getContext("2d");

function drawAndPrepareDownload() {
  // Scale the entire source image into the 600 × 400 output.
  // This may change its aspect ratio. See the crop example below
  // when the output should preserve the source's proportions.
  context.drawImage(image, 0, 0, canvas.width, canvas.height);

  const jpegUrl = canvas.toDataURL("image/jpeg", 0.9);
  const link = document.createElement("a");
  link.href = jpegUrl;
  link.download = "landscape.jpg";
  document.body.appendChild(link);
  link.click();
  link.remove();
}

image.addEventListener("load", drawAndPrepareDownload, { once: true });
image.addEventListener("error", () => {
  console.error("The source image could not be loaded.");
}, { once: true });

// Handle an image that was already loaded before the listeners were attached.
if (image.complete && image.naturalWidth > 0) {
  drawAndPrepareDownload();
}

Attach load and error handlers before assigning a new source when loading dynamically, so a fast response cannot finish before the handlers are registered:

function loadImage(url) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener("load", () => resolve(image), { once: true });
    image.addEventListener("error", () => reject(new Error(`Could not load ${url}`)), { once: true });
    image.src = url;
  });
}

async function render() {
  try {
    const image = await loadImage("/images/landscape.jpg");
    const canvas = document.createElement("canvas");
    canvas.width = 600;
    canvas.height = 400;
    canvas.getContext("2d").drawImage(image, 0, 0, 600, 400);
    document.body.append(canvas);
  } catch (error) {
    console.error(error);
  }
}

render();

Crop a source rectangle

The nine-argument form of drawImage() selects a source rectangle and maps it to the output canvas. Here, the center square of an image is cropped and scaled to a 400-by-400 bitmap:

function centerSquareCrop(image) {
  const side = Math.min(image.naturalWidth, image.naturalHeight);
  const sx = (image.naturalWidth - side) / 2;
  const sy = (image.naturalHeight - side) / 2;
  const canvas = document.createElement("canvas");
  canvas.width = 400;
  canvas.height = 400;

  canvas.getContext("2d").drawImage(
    image,
    sx, sy, side, side,       // source rectangle
    0, 0, canvas.width, canvas.height // destination rectangle
  );

  return canvas;
}

Export with canvas.toBlob() when you want a Blob instead of an in-memory data URL. A Blob is often more suitable for larger outputs; a data URL encodes the bytes into a string.

canvas.toBlob((blob) => {
  if (!blob) {
    console.error("Canvas export failed.");
    return;
  }

  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = "landscape-crop.jpg";
  link.click();
  URL.revokeObjectURL(objectUrl);
}, "image/jpeg", 0.9);

Canvas and cross-origin images

For a remote image, set crossOrigin before src if the server is configured to allow a cross-origin request:

const image = new Image();
image.crossOrigin = "anonymous"; // Set before src.
image.onload = () => {
  const canvas = document.createElement("canvas");
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  canvas.getContext("2d").drawImage(image, 0, 0);
  // Pixel reads or export require an origin-clean canvas.
  console.log(canvas.toDataURL("image/png"));
};
image.onerror = () => console.error("Image load or CORS request failed.");
image.src = "https://images.example.org/photo.jpg";

The remote server must grant access through CORS. Setting crossOrigin on the image only makes a CORS request; it cannot make a server permit it. Without the required permission, the browser may display the image but prevent reading pixels or exporting the canvas.

6. Choose the right approach

Goal Approach Does it create a new image bitmap?
Add or replace an image in the page jQuery .attr() and .append() No
Offer different image resources for screen conditions srcset/sizes or <picture> No
Resize or crop how an image appears in a layout CSS sizing and object-fit No
Crop, scale, or draw pixels and export a result Canvas drawImage() and export Yes
Transform files outside the browser or in bulk An image-processing service or server-side library Yes

Use a browser canvas for interactive, client-side work. For a server workflow, large batches, or transformations that must be reproducible regardless of a visitor’s browser, use an image-processing service or server-side tooling. The right choice depends on where the source image lives, whether the result must be exported, and whether CORS permits canvas access.

7. Troubleshooting

Symptom Likely cause Fix
The image does not appear The URL is wrong, the request failed, or the file is unavailable. Inspect the browser’s network panel and the image’s error event; verify the path and response.
Canvas export throws a security error A cross-origin image tainted the canvas because the server did not allow the requesting origin. Serve the image from the same origin or configure its server to permit the origin; set crossOrigin before src.
Canvas is blank Drawing happened before the image loaded, or the source failed. Wait for load, check naturalWidth, and handle error.
The image looks stretched The destination width and height use a different ratio from the source. Preserve the ratio, or intentionally crop using the source-rectangle drawImage() overload.
The CSS crop is not in the exported file object-fit changes display only. Use canvas to draw and export the desired crop.
Layout jumps when an image loads The browser did not know the image’s dimensions in advance. Set intrinsic width and height attributes or otherwise reserve the aspect ratio.
The wrong responsive source appears sizes does not describe the rendered slot, or candidate descriptors are incorrect. Match sizes to actual layout widths and use valid width or density descriptors consistently.
jQuery reports that $ is undefined jQuery has not loaded before the application script. Load the jQuery script first and check for a failed script request.

8. Performance, reliability, and cost

Prefer appropriately sized source files and responsive candidates so the browser does not needlessly fetch a larger image for a smaller slot. Give images dimensions to reduce layout shifts, and lazy-load suitable offscreen content. Avoid lazy-loading the lead image that is likely visible at page load.

Canvas work uses browser memory for image pixels and the output surface. Avoid repeatedly creating oversized canvases for small previews; size the output to the result you need, release object URLs after use, and handle load and export failures. A canvas operation only works reliably when the image has loaded and the canvas remains origin-clean.

Browser-side display changes and canvas operations have no ScreenshotNeo API charge, though they use the visitor’s device and network. If the job is to capture a rendered webpage as an image or PDF rather than modify an image bitmap, a screenshot API is a separate option. ScreenshotNeo’s free tier includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. The full feature set is available on every plan.

9. Or skip the browser setup

If your goal is a screenshot of a webpage, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. See the API documentation for parameters.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000. Sign up for free and capture your first 1,000 screenshots a month without a card.

10. FAQ

Can jQuery resize an image?

Yes, for how it appears on the page, by setting CSS dimensions. To create and export a resized bitmap, use canvas or image-processing tooling.

Can I crop an image with jQuery?

jQuery can set CSS such as object-fit: cover for a visual crop. For a cropped file, draw a source rectangle to canvas and export it.

Should I put image descriptions in title or alt?

Use alt for the image’s text alternative. A title attribute is not a substitute for necessary alternative text or visible instructions.

Can I export any image shown in the browser?

No. Canvas pixel access and export depend on the canvas remaining origin-clean. For remote sources, the image server must allow the cross-origin request.

References