Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change CSS attributes of my image in javascript?

I created a new image but I'm trying to resize it and add some transformations to it. How ever, they are not taking effect.

Example: https://jsfiddle.net/chung9ey/3/

img.onload = function(){
    img.style.width = "500";
    img.style.height = "300";
    img.style.transform = "perspective(500px) rotateZ(30deg)";
    context.drawImage(img, 0 ,0);   
}
like image 438
user6432770 Avatar asked Jul 06 '16 20:07

user6432770


Video Answer


3 Answers

Styles change properties, not attributes. In order to change the actual attributes you would need to use

img.height = 300;

//or by native API
img.setAttribute("height",300);

and so on for each attribute you wanted to change. Note that attributes are part of the html element and not necessarily part of the css definition (more on that here: https://www.w3.org/TR/CSS21/cascade.html#preshint).

like image 197
Travis J Avatar answered Oct 14 '22 08:10

Travis J


Try using this.

document.getElementById("imageID").style.height="300px";
document.getElementById("imageID").style.width="500px";

That should change the element's style width and height to what you want. In the HTML script, it'd be

<img src="source.jog" id="imageID"/>
like image 38
Dragg Avatar answered Oct 14 '22 07:10

Dragg


Based on this Stack Overflow answer, change your JS to:

var img = new Image();
var canvas = document.getElementById("hello");
var context = canvas.getContext("2d");

img.onload = function(){
  context.save(); // Saves current canvas state (includes transformations)
  context.rotate(30); // This rotates canvas context around its top left corner...
  context.translate(-275, 125); // ...so you need to make a correction.
  context.drawImage(img, 0, 0, 500, 300);   
  context.restore(); // Restore canvas state
};

img.src = "https://www.enterprise.com/content/dam/global-vehicle-images/cars/CHRY_200_2015.png";

This essentially rotates the canvas's contents after the image is drawn on it.

Part of the image is off-canvas as a result of this rotation, so you may also want to scale the canvas to fit the rotated image.

https://jsfiddle.net/Lcyksjoz/

like image 21
jkdev Avatar answered Oct 14 '22 09:10

jkdev