Skip to main content

Rendering part of the image

How to take generate part of image.

In this example, we will demonstrate how to use the selector parameter to render only a specific part of an image. The selector parameter allows you to target and capture a specific element within the HTML content.

selector param

The selector parameter is used to specify a CSS selector that corresponds to an element in the HTML. The image will be cropped precisely to this designated element.

Example HTML Content

Here is an example HTML content that we will use:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>

And CSS part:

    body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}

Here is rendered image:

Rendered code

Using selector param

Using the selector parameter with the value .highlighted, we can capture the paragraph with the "highlighted" class:

Rendered using selector

Code examples

import requests

url = 'https://api.canvasflare.com/render?api_key=YOUR_API_KEY'

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>
'''

css = '''
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}
'''

# Specify the CSS selector for the element you want to capture
selector = ".highlighted"

# Set other parameters like device_scale, viewport_width, etc.

response = requests.post(url, data={'html': html, 'css': css, 'selector': selector})

if response.status_code == 200:
image_url = response.json()['imageUrl']
print(f"Image URL: {image_url}")
else:
print(f"Error creating image: {response.status_code}")