我有一个图像的base64字符串,必须将其显示为图标。如果图像的尺寸较大,我必须显示保持宽高比的图标。 我已经写了一个逻辑,可以根据画布的高度和宽度确定图像是横向还是纵向。但是似乎图标的高度和宽度不合适,因为我已经对其进行了硬编码。
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var height, width;
if (this.height>this.width) {
height = 50;
width = 30;
} else if (this.height<this.width) {
height = 30;
width = 50;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(image,
0, 0, this.width, this.height,
0, 0, canvas.width, canvas.height
);
var scaledImage = new Image();
scaledImage.src = canvas.toDataURL();
有没有什么方法可以动态计算它,或者有其他方法可以保留图标的长宽比。
工作示例可以在https://codepen.io/imjaydeep/pen/ewBZRK
上找到在x-y轴上留一些空间会很好。
答案 0 :(得分:1)
您只需要计算比例尺或比例,然后将两个尺寸相乘即可。这是一个示例函数,这是您的edited codepen。
创建修剪的缩放图像:
$ mkdir example
$ cd example
$ gradle -v
------------------------------------------------------------
Gradle 5.4.1
------------------------------------------------------------
Build time: 2019-04-26 08:14:42 UTC
Revision: 261d171646b36a6a28d5a19a69676cd098a4c19d
Kotlin: 1.3.21
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 1.8.0_151 (Oracle Corporation 25.151-b12)
OS: Mac OS X 10.14.5 x86_64
$ gradle init
Select type of project to generate:
...
8: kotlin-application
9: kotlin-library
Enter selection (default: basic) [1..10] 8
Select build script DSL:
1: groovy
2: kotlin
Enter selection (default: kotlin) [1..2] 2
Project name (default: example):
Source package (default: example):
$ ./gradlew build
BUILD SUCCESSFUL in 1s
$ ./gradlew run
> Task :run
Hello world.
BUILD SUCCESSFUL in 0s
$ ./build/scripts/example
Error: Could not find or load main class example.AppKt
$ jar tf build/libs/example.jar
META-INF/
META-INF/MANIFEST.MF
example/
example/AppKt.class
example/App.class
META-INF/example.kotlin_module
$ cat build.gradle.kts
plugins {
id("org.jetbrains.kotlin.jvm").version("1.3.21")
application
}
repositories {
jcenter()
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
application {
mainClassName = "example.AppKt"
}
$ cat src/main/kotlin/example/App.kt
package example
class App {
val greeting: String
get() {
return "Hello world."
}
}
fun main(args: Array<String>) {
println(App().greeting)
}
或者,如果您希望图像始终是提供的尺寸且周围区域为空,则可以使用以下方法:(codepen)
创建精确提供尺寸的缩放图像:
function scaleDataURL(dataURL, maxWidth, maxHeight){
return new Promise(done=>{
var img = new Image;
img.onload = ()=>{
var scale, newWidth, newHeight, canvas, ctx;
if(img.width < maxWidth){
scale = maxWidth / img.width;
}else{
scale = maxHeight / img.height;
}
newWidth = img.width * scale;
newHeight = img.height * scale;
canvas = document.createElement('canvas');
canvas.height = newHeight;
canvas.width = newWidth;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight);
done(canvas.toDataURL());
};
img.src = dataURL;
});
}