简体   繁体   中英

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);   
}

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 ).

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"/>

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/

i would change the image size in the canvas and then manipulating the canvas through id

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

var width = 500;
var height = 300;
img.onload = function(){
    img.style.transform = "perspective(200px) rotateZ(30deg)";
    context.drawImage(img, 0 ,0, width,height); 
}

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

document.getElementById("hello").style.width="300px";

https://jsfiddle.net/chung9ey/27/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM