Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
Canvas

How to Add a Graph to an Image With HTML and CSS

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the image and graph in the same position: relative wrapper, then position the graph layer over it. Give both layers the same responsive dimensions so they stay aligned as the image changes size. Use HTML/CSS for labels and simple overlays, inline SVG for crisp vector graphs, or canvas when you need to export the combined result as one bitmap.

The basic HTML and CSS overlay

An overlay is made of two layers: a base image and a graph layer above it. The wrapper establishes the coordinate space; the graph’s absolute positioning places it within that space. For static placement, CSS is enough—Google’s Charts documentation notes that simple overlays can use a CSS class referenced in HTML, with no JavaScript required (Google Charts overlays).

<div class="image-chart">
  <img src="photo.jpg" alt="Sales region map">
  <div class="graph" role="img" aria-label="Quarterly sales graph">
    <!-- Put inline SVG, a canvas, or chart output here. -->
  </div>
</div>
.image-chart {
  position: relative;
  width: min(100%, 900px);
  aspect-ratio: 16 / 10;
  margin-inline: auto;
}

.image-chart > img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.graph {
  position: absolute;
  inset: 10% 8% 12% 12%;
  pointer-events: none;
}

The wrapper’s aspect ratio should correspond to the image’s displayed shape. The inset shorthand sets the graph area’s top, right, bottom, and left edges as percentages of the wrapper. Here the graph covers the central portion of the picture, leaving room around it. Change those values to put the graph where the image has clear space.

Use one coordinate system for both layers

The image and overlay must scale together. If the wrapper grows or shrinks while the graph keeps fixed pixel dimensions, the graph will drift or cover the wrong area. Percentage insets, an SVG viewBox, or drawing coordinates scaled from the canvas dimensions all provide a way to keep the graph proportional.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Be aware of image cropping: object-fit: cover fills the wrapper but can crop part of the original image. If exact points on the source image matter, make the wrapper’s aspect ratio match the source and avoid cropping. Otherwise, adjust the graph to match the displayed crop, not the uncropped file.

Decide whether the graph should receive pointer input

The example uses pointer-events: none, allowing clicks to pass through to the image or elements underneath. Remove that declaration if graph controls, tooltips, or other interactive content need to receive pointer input. For interactive controls, provide keyboard access and visible focus styles too.

Choose the graph technology that fits the job

Approach Best for Trade-off
HTML/CSS overlay Labels, annotations, or a separate graph positioned over a responsive image Positions are tied to layout and need adjustment if the image’s crop changes
Inline SVG Scalable vector lines, bars, and annotations that need styling or script-driven updates Requires SVG markup; SVG used as an image has restrictions on scripts and external resources
Canvas Pixel-based drawing, numerous marks, or a combined raster export Accessibility must be supplied separately; a CSS background is not part of the exported bitmap
Chart library Data-driven scales, updates, and library-provided chart behavior Overlay and export techniques depend on the library

MDN describes SVG as usable as an image format in HTML, CSS, certain SVG elements, and through the Canvas API (MDN: SVG). For an interactive or programmatically updated graph, inline SVG is generally more flexible than loading an SVG as an image; MDN documents limits on JavaScript and external resources in image contexts (MDN: SVG as an image).

Use inline SVG for a scalable graph

SVG is a good fit for a line or bar graph that should remain sharp at different sizes. Its viewBox defines a coordinate system independent of its rendered dimensions, so it can scale with the wrapper. Inline markup can be styled with CSS and updated with JavaScript if the data changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<div class="image-chart">
  <img src="product.jpg" alt="Product displayed on a workbench">
  <svg class="graph" viewBox="0 0 100 60"
       role="img" aria-label="Monthly revenue trend">
    <polyline points="0,50 20,42 40,45 60,25 80,30 100,10"
              fill="none" stroke="crimson" stroke-width="2" />
  </svg>
</div>
.image-chart svg.graph {
  position: absolute;
  inset: 10% 8% 12% 12%;
  width: 80%;
  height: 78%;
  overflow: visible;
}

The SVG’s accessible name should describe the information conveyed, not merely say “graph.” If the chart has detailed values, include an equivalent text description or data table nearby; a short label alone cannot communicate every plotted value.

A CSS background image can be suitable for a decorative, static SVG, but it is not the right place for interactive chart logic. An SVG loaded as an image has restrictions on scripts and external resources, unlike SVG markup embedded directly in the page (MDN: SVG as an image).

Use canvas when you need one exported image

Canvas is appropriate when JavaScript draws many marks or computes graph pixels, or when the final output needs to be a single raster image. A canvas can be placed over an image with CSS, but there is an important distinction: a CSS background displayed behind the canvas drawing is not included in the canvas bitmap. Apple’s canvas documentation describes this behavior (Apple: Adding a background to a canvas).

To export the composition, draw the source image into the canvas first, then draw the graph over it. This example assumes the image is same-origin or served with appropriate cross-origin access; see the troubleshooting section for export failures.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<canvas id="graph" aria-label="Revenue trend over a product photo">
  Revenue rises through the final quarter.
</canvas>

<script>
const canvas = document.querySelector('#graph');
const ctx = canvas.getContext('2d');
const image = new Image();

image.onload = () => {
  const cssWidth = 900;
  const cssHeight = 560;
  const scale = window.devicePixelRatio || 1;

  canvas.width = cssWidth * scale;
  canvas.height = cssHeight * scale;
  canvas.style.width = `${cssWidth}px`;
  canvas.style.height = `${cssHeight}px`;
  ctx.scale(scale, scale);

  ctx.drawImage(image, 0, 0, cssWidth, cssHeight);
  ctx.beginPath();
  ctx.moveTo(90, 440);
  ctx.lineTo(270, 360);
  ctx.lineTo(450, 380);
  ctx.lineTo(630, 220);
  ctx.lineTo(810, 130);
  ctx.strokeStyle = 'crimson';
  ctx.lineWidth = 4;
  ctx.stroke();
};

image.onerror = () => {
  console.error('Could not load the source image.');
};
image.src = 'photo.jpg';
</script>

In a responsive page, choose the canvas’s CSS dimensions from its rendered size and set the bitmap dimensions to those dimensions multiplied by the device pixel ratio. Scale the drawing context accordingly, as above. If you resize the canvas later, redraw the image and graph: changing its bitmap dimensions clears the existing pixels.

Chart-library overlays and exports

With a data-driven library, use its own overlay hooks when the graph changes or annotations must follow data points. Google Charts describes calculating data-dependent placement after its ready event with coordinate methods (Google Charts overlays). For a combined Chart.js export, the documentation says there is no built-in support and points to a custom plugin approach (Chart.js: canvas background). Do not assume that a background shown on screen will automatically appear in a chart’s exported file.

Make the overlay responsive and readable

  • Keep the image and graph inside the same positioned wrapper; avoid positioning the graph against the viewport or an unrelated ancestor.
  • Use percentage insets or vector coordinates when the graph should scale proportionally with the image.
  • Verify alignment at narrow and wide viewport sizes, especially when the image uses object-fit: cover.
  • Check contrast against every part of the photograph beneath the graph. A semi-opaque panel, outline, or shadow can improve legibility without changing the coordinate model.
  • Describe the graph with an accessible name, and provide equivalent text or data where its content matters.
  • If the graph is interactive, do not disable pointer events; make controls operable by keyboard as well.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common overlay problems

The graph is behind the image

Confirm that the wrapper has position: relative and the graph has position: absolute. If another positioned layer overlaps it, set an appropriate z-index on the graph and check whether an ancestor’s stacking context is affecting the order.

The graph moves out of alignment when the image resizes

Check that both layers use the same wrapper and that graph coordinates scale with it. Replace fixed pixel offsets with percentage insets or an SVG viewBox. Also confirm the displayed image is not being cropped differently at the size where alignment fails.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

The graph is clipped or covers the wrong area

Inspect the wrapper’s aspect ratio and the image’s object-fit behavior. If cover crops the source, either choose a matching wrapper ratio, use object-fit: contain, or recalibrate the graph for the crop that is actually displayed.

The canvas looks sharp on screen but blurry in a saved file

The canvas bitmap may be smaller than its CSS display size. Set its pixel width and height to the CSS dimensions multiplied by window.devicePixelRatio, then scale the drawing context and redraw. Keep bitmap dimensions and CSS dimensions distinct.

The canvas export fails after drawing a remote image

A remote image without the required cross-origin permission can taint a canvas, preventing pixel export. Serve the image from the same origin or configure the image host to allow the page’s origin, and set the image’s cross-origin mode before assigning its URL. A CSS background will not solve this export issue, because CSS backgrounds are not canvas pixels in the first place.

Clicks do not reach graph controls

Remove pointer-events: none from the overlay or the relevant control. Conversely, if the graph is only visual and blocks clicks meant for content beneath it, keep that rule on the graph layer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If you need a screenshot of a web page showing the image and graph, ScreenshotNeo can return a screenshot or PDF from one request. Cookie banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. See the ScreenshotNeo website or its API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/page-with-graph -o shot.webp

Sign up free for 1,000 screenshots a month, with no card required.

Frequently Asked Questions

Can I make a graph overlay without JavaScript?

Yes. A static HTML/CSS overlay or inline SVG with fixed graph content needs no JavaScript. JavaScript is needed when drawing or updating canvas pixels or when calculating positions from changing chart data.

Will a CSS background be included when I export a canvas?

No. A CSS background can display behind canvas drawing, but it is not part of the canvas bitmap. Draw the image into the canvas before drawing the graph.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.