Issue #2705Opened April 7, 2020by andy-aware2 reactions

[Question] Adding image sizes to image

Question

When I add an image attribute to the page I noticed that inside of the component the image has attributes to it.

When I call my images into the asset manager I do it like the following:

    type: 'image',
    src: 'http://placehold.it/350x250/459ba8/fff/image2.jpg',
    height: 350,
    width: 250

However, the height and width aren't available when the image gets added to the canvas. I've tried to get the sizes by doing:

component.views[0].el.height

and adding it to the object, but every time I try I get 0 because the image isn't available in the DOM yet, so it doesn't know what size it is.

Is there a way to pass these heights and widths to the image, I need this for some lazy load functions I'm doing. I'm currently doing this on an update

editor.on('component:update', component => {
    const item = component.attributes.attributes;
			
    // item['width'] = component.view.el.width;
    // item['height'] = component.view.el.height;

    console.log(editor.AssetManager.getAll());
    console.log('Comp:', component.views[0].el.height);
    //console.log(image.naturalWidth);
			
});

Should i be adding to the attributes earlier than this?

Thanks.

Answers (3)

artfApril 20, 20202 reactions

@awaredigital probably the best solution would be to follow the suggestion to listen up to src changes, then find the right asset and update attributes accordingly

model: {
	init() {
		this.on('change:src', this.onSrcUpdate);
	},
	onSrcUpdate() {
		const src = this.get('src');
		const assets = editor.AssetManager.getAll();
		const asset = assets.filter(asset => asset.get('src') == src)[0];
		if (asset) {
			const width = asset.get('width');
			width && this.addAttributes({ width });
			// ...
		}
	}
}
pouyamiralayiApril 9, 20200 reactions

Hi @awaredigital checkout #2696 comment which is updating the styles whenever the src changes. Cheers!

andy-awareApril 9, 20200 reactions

Hi @pouyamiralayi, thanks for the answer but that isn't what I'm looking to do. I'm looking to add height and width to the image element itself. So for example at the moment, the image goes in like this:

<img src="http://placehold.it/350x250/459ba8/fff/image2.jpg" id="123" />

What I want to do is insert the image with the according height and width.

<img src="http://placehold.it/350x250/459ba8/fff/image2.jpg" id="123" height="350" width="250" />

However, I can't see how to do this.

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.