2016-07-06 48 views
5

我创建了一个新的图像,但我试图调整它的大小并添加一些转换。如何,他们没有生效。为什么我不能在javascript中更改图像的CSS属性?

实施例: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); 
} 
+2

你需要比其它数值CSS长度值的单元'0' – dandavis

+0

它应该是'context.drawImage(IMG,topLeftCornerHorizo​​ntalPosition,topLeftCornerVerticalPosition,imageWidth,imageHeight);'。请参阅https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage – jkdev

+0

至于向画布添加旋转图像,可能无法使用'img.style.transform'。请参阅[旋转并保存JavaScript的图像](http://stackoverflow.com/q/34080762/3345375)。 – jkdev

回答

4

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

img.height = 300; 

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

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

+0

但更改样式属性将使样式更改生效。 – Barmar

+0

@Barmar - 不,不总是。 –

+0

@Barmar:要么工作。 OP应该使用正确的CSS(修正微小的错字)来使用他现有的例程,但是这个答案是有效的,因为默认的用户代理样式。 – dandavis

1

试着用这个。

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

这应该将元素的样式宽度和高度更改为所需。 在HTML脚本,它会是

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

@dandavis我不这样做,但它可以改变为图像的ID是。 – Dragg

+0

@TravisJ我不好。 – Dragg

+0

如果你有图像本身的句柄(这里是'img'),你不需要'id'。 – jkdev

0

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

1

基于this Stack Overflow answer,改变操纵画布您的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"; 

T在绘制图像之后,他基本上旋转画布的内容。

由于此旋转,图像的一部分是非画布的,因此您可能还需要缩放画布以适应旋转的图像。

https://jsfiddle.net/Lcyksjoz/

相关问题