Searching for the parent div's class name can be achieved by using various methods

My current canvas size is set within the col-sm-6 bootstrap class. However, I would like to display a larger canvas if it falls within the col-sm-12 bootstrap class. The classes col-sm-6 and col-sm-12 are generated dynamically from the backend, so I need to determine if the canvas is within the col-sm-6 or col-sm-12 class in order to adjust the width accordingly.

The first, smaller canvas could be sized at 500*400:

<div class="s-field col-sm-6">
    <label class="control-label mb5">first canvas image </label>
    <canvas  id="canvas-id-1" class="image-canvas"></canvas>
</div>

The second canvas should be larger, maybe 800*400:

<div class="s-field col-sm-12">
    <label class="control-label mb5">second canvas image </label>
    <canvas  id="canvas-id-2" class="image-canvas"></canvas>
</div>
let canvas = document.getElementById('canvas-id');
let ctx = canvas.getContext("2d");
// If I know that the canvas is within the class col-sm-12, I can set dimensions to 800*400
if (document.querySelector('.col-sm-12')) {
  canvas.width = 800;
  canvas.height = 400;
} else {
  // Otherwise, I will create a smaller canvas
  canvas.width = 500
  canvas.height = 400
}

var image = new Image();
image.src = 'http://t2.gstatic.com/images?q=tbn:ANd9GcQQveW9AJCxOC8Phnq3vptJIxPFHlxNw63q4pudc66dM4O96vtm';
image.onload = function () {
  var ctx = canvas.getContext('2d');
  ctx.drawImage(image,
    canvas.width / 2 - image.width / 2,
    canvas.height / 2 - image.height / 2
  );
}

Answer №1

There seems to be a mistake in your code: "cxt.drawImage" should actually be "ctx.drawImage".

for (let canvas of document.querySelectorAll ('.image-canvas')) {
  let ctx = canvas.getContext("2d");
  if (canvas.parentNode.classList.contains('col-sm-12')) {
    canvas.width = 800;
    canvas.height = 400;
  } else {
    canvas.width = 500
    canvas.height = 400
  }
  let image = new Image();
  image.src = 'http://t2.gstatic.com/images?q=tbn:ANd9GcQQveW9AJCxOC8Phnq3vptJIxPFHlxNw63q4pudc66dM4O96vtm';
  image.onload = function () {
    ctx.drawImage (image,
      canvas.width / 2 - image.width / 2,
      canvas.height / 2 - image.height / 2
    );
  }
}
  
canvas {
  border: 1px solid black;
}
<div class="s-field col-sm-6">
    <label class="control-label mb5">first canvas image </label>
    <canvas  id="canvas-id-1" class="image-canvas"></canvas>
</div>

<div class="s-field col-sm-12">
    <label class="control-label mb5">second canvas image </label>
    <canvas  id="canvas-id-2" class="image-canvas"></canvas>
</div>

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

Using the Angular translate filter within a ternary operator

I am currently working on translating my project into a different language. To do this, I have implemented the Angular Translate library and uploaded an external JSON file containing all the translations. Here is an example of how it looks: { "hello_wor ...

Boost Script - when you move your mouse

Seeking assistance and truly grateful for any help! I came across an image magnifier on Dynamic Drive, but it's not exactly what I need. It's great except for one thing - I don't want the user to click on the image to view it, I want them t ...

Spacing issue with Angular Material causing layout problems

I've been attempting to implement 'space between center' in a row, but it doesn't seem to be working as intended: <div layout="row" layout-sm="column" layout-align="space-between center" hide-xs> <div layout="colum ...

The text input field is unresponsive and unable to be selected in the mobile layout

I have implemented this <textarea> component within my web application <div class="col-xs-11 lessSpaceBetweenLine"> <textarea class="form-control actionitems" id="actionitems" name="actionitems" rows="2" pl ...

Interactive form design using Bootstrap - combining labels, input fields, and buttons in a streamlined inline

Looking for a clean HTML markup without the need for custom CSS like Bootstrap, my goal is to achieve a design similar to the demo I created on bootply - http://www.bootply.com/1Uy4UROiEz The only issue with the above demo is that I want the go button to ...

Having trouble retrieving the state name within the directive controller

When trying to access $state.current.name from a directive controller, it always appears to be blank. Is it possible that the directive loads before the state evaluation process? If so, what would be a suitable workaround for this issue? The goal is to dis ...

Tips for implementing mongoDB regex in an Express application

Is there a way to use regex in MongoDB to filter results based on a specific query parameter in the URL? I attempted to use $regex syntax in the query.find() method but it did not provide the expected outcomes. Appreciate any help with this, thank you. C ...

Can a script be dynamically loaded into a div while accessing local variables?

Consider the scenario where you have two files: test.html <div id="stuff"></div> <button onclick="doStuff()">Magic</button> <script> var foo = new function() { this.bar = function() { return "THE MAGIC!"; }; ...

Guidelines for sending data as an array of objects in React

Just starting out with React and I have a question about handling multi select form data. When I select multiple options in my form, I want to send it as an array of objects instead of an array of arrays of objects. Can anyone help me achieve this? import ...

Is it possible to utilize an alias in conjunction with the NodeJS require function?

I have a JavaScript module written in ES6 that exports two constants: export const apple = "apple"; export const banana = "banana"; In another module, I can import these constants as follows: import { apple as a, banana as b } from 'fruits'; c ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

Is it possible to utilize the Linear-gradient property for creating a vertical background color effect?

I'm currently attempting the following: body { height:100%; background: -moz-linear-gradient(left, #DB2B39 50%, #2B303A 50%); background: -webkit-linear-gradient(left, #DB2B39 50%,#2B303A 50%); background: linear-gradient(to right, #D ...

The functionality of onClick or onChange seems to be malfunctioning in the preline user interface select component

I recently integrated the preline UI library into my React project to enhance the design of my website. However, I encountered an issue where using the "select" element with the data-hs-select attribute as suggested by preline UI seemed to cause problems w ...

Display content in the View in ASP.NET based on the parameters passed into the ActionResult function

I'm grappling with a theoretical scenario involving rendering a single View with different content based on user input using MVC in the .NET framework. Essentially, I'm looking to have just one page titled "Create Template", but its contents sho ...

Fixing the issue of list styles not displaying properly when using CSS3 columns in Webkit can be achieved by

example here: http://jsfiddle.net/R7GUZ/3/ I'm struggling to make the list-style property work in webkit for a parent OL that is styled with -webkit-column-count: 2; -moz-column-count: 2; column-count: 2; Is there a way to format an ordered list ...

The Flot chart is experiencing difficulties displaying time and count data

Hello, I am currently working on creating a flot graph and I have been using this plugin found at . My goal is to display time (h:m) on the x-axis and counts on the y-axis. I have written a script for this purpose, but unfortunately, it's not functio ...

Is there a way to retrieve four random documents from a MongoDB collection using Node.js?

What is the best way to retrieve 4 random documents from MongoDB using node/express.js? I know how to set a limit for the number of retrieved documents, but not specifically for random selection. Any suggestions on how to achieve this? ...

Mastering the art of styling strings in the Terminal with Chalk - the ultimate guide

I've been trying to use the chalk terminal string styling package in iTerm2, but I'm not seeing any colored string results despite following all the installation steps. Even a simple console log like console.log("hello"); in my chalk.js file isn& ...

Exploring the power of CSS using :after and :nth-child selectors

.app-btn { font-size: 0px !important; } .app-btn:after { content: '+2500'; visibility: visible; font-size: 15px !important; } .app-btn:after:nth-child(1) { content: "+18000"; } .app-btn:after:nth-child(2) { content: "+14000"; } < ...

Maintain Vue Router Query Parameters Across Parent Components

In my application, I have a component named Foo, which serves as the template for a route called app/foo. Within this component, there are child components that also act as templates for routes such as app/foo/bar and app/foo/baz. I've implemented a ...