繁体   English   中英

为什么我不能在javascript中更改我的图像的CSS属性?

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

我创建了一个新图像,但我正在尝试调整它并为其添加一些转换。 然而,他们没有生效。

示例: 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);   
}

样式更改属性,而不是属性。 要更改您需要使用的实际属性

img.height = 300;

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

对于您想要更改的每个属性等等。 请注意,属性是html元素的一部分,并不一定是css定义的一部分(更多内容在此处: https//www.w3.org/TR/CSS21/cascade.html#preshint )。

试试这个。

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

这应该将元素的样式宽度和高度更改为您想要的。 在HTML脚本中,它是

<img src="source.jog" id="imageID"/>

基于此Stack Overflow答案 ,将您的JS更改为:

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

这实际上是在绘制图像后旋转画布的内容。

由于此旋转,部分图像在画布外,因此您可能还需要缩放画布以适合旋转的图像。

https://jsfiddle.net/Lcyksjoz/

我会改变画布中的图像大小,然后通过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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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