javascript - canvas图片缩放问题
本文介绍了javascript - canvas图片缩放问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
canvas图片缩放时候已经用ctx.clearRect(0 , 0,canvas.width,canvas.heihgt); 对画布清理,演示效果却是下面这样,请高手解惑。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas image processing | 镜心书社 </title>
</head>
<body style="background-color: black">
<canvas id="canvas" style="display: block; margin: 0 auto;border: 1px solid #aaa;">
你的浏览器尚不支持canvas
</canvas>
<input type="range" name="" style="display: block;margin: 20px auto;width: 800px" id="scale-range" min="0.5" max="3.0" step="0.01" value="1.0" />
<script type="text/javascript">
var canvas =document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var slider=document.getElementById("scale-range");
var image= new Image();
window.onload= function(){
canvas.width=1152;
canvas.height=768;
var scale=slider.value;
image.src="../images/img.jpg";
image.onload=function(){
drawImageByScale(scale);
slider.onmousemove=function(){
scale=slider.value;
drawImageByScale(scale);
}
//ctx.drawImage(image,0,0,canvas.width,canvas.height);
// ctx.drawImage(image,600,200,400,400,0,0,400,400)
}
};
function drawImageByScale(scale){
var imageWidth=canvas.width*scale;
var imageHeight=canvas.width*scale;
// var sx=imageWidth/2-canvas.width/2;
// var sy=imageHeight/2-canvas.height/2;
// ctx.drawImage( image , sx , sy, canvas.width , canvas.height , 0 , 0 , canvas.width , canvas.height);
var dx=(canvas.width-imageWidth)/2;
var dy=(canvas.height-imageHeight)/2;
ctx.clearRect(0 , 0,canvas.width,canvas.heihgt);
ctx.drawImage(image,dx,dy,imageWidth,imageHeight);
}
</script>
</body>
</html>
解决方案
function drawImageByScale(scale){
var imageWidth=canvas.width*scale;
var imageHeight=canvas.width*scale;
// var sx=imageWidth/2-canvas.width/2;
// var sy=imageHeight/2-canvas.height/2;
var dx=(canvas.width-imageWidth)/2;
var dy=(canvas.height-imageHeight)/2;
/*
注意这里 heihgt ????????
height !
*/
ctx.clearRect(0 , 0,canvas.width,canvas.heihgt);
ctx.drawImage(image,dx,dy,imageWidth,imageHeight);
}
下次这种问题希望可以提供 jsfiddle 链接
这篇关于javascript - canvas图片缩放问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文